<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\SmsMessage;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CampaignStatusApiController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $userId = $request->user()->id;
        $batchId = $request->input('batch_id', $request->input('id'));

        if (!$batchId) {
            return response()->json(['status' => 4022, 'message' => 'Batch ID is required.'], 422);
        }

        $messages = SmsMessage::where('user_id', $userId)
            ->where('batch_id', $batchId)
            ->get();

        if ($messages->isEmpty()) {
            return response()->json(['status' => 4004, 'message' => 'Batch campaign not found.'], 404);
        }

        $counts = [
            'total' => $messages->count(),
            'pending' => $messages->where('status', SmsMessage::STATUS_PENDING)->count(),
            'processing' => $messages->where('status', SmsMessage::STATUS_PROCESSING)->count(),
            'sent' => $messages->where('status', SmsMessage::STATUS_SENT)->count(),
            'failed' => $messages->where('status', SmsMessage::STATUS_FAILED)->count(),
        ];

        return response()->json([
            'status' => 2000,
            'success' => true,
            'data' => [
                'batch_id' => $batchId,
                'counts' => $counts,
                'messages' => $messages->take(100),
            ],
        ]);
    }
}
