<?php

namespace App\Http\Controllers\Api\Tasks;

use App\Domains\Tasks\Actions\BuildFollowUpCampaignAudienceAction;
use App\Domains\Tasks\Actions\ExecuteFollowUpCampaignAction;
use App\Domains\Tasks\Models\FollowUpCampaign;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class FollowUpCampaignApproveController extends Controller
{
    public function __invoke(
        Request $request,
        string $campaign,
        BuildFollowUpCampaignAudienceAction $buildAudience,
        ExecuteFollowUpCampaignAction $executeCampaign
    ): JsonResponse {
        $record = FollowUpCampaign::query()
            ->where('tenant_id', $request->user()->tenant_id)
            ->findOrFail($campaign);

        $validated = $request->validate([
            'run_now' => ['nullable', 'boolean'],
        ]);
        $runNow = (bool) ($validated['run_now'] ?? true);

        $record->update([
            'approved_by' => $request->user()->getKey(),
            'approved_at' => now(),
            'status' => 'scheduled',
        ]);

        if ($runNow) {
            $filters = is_array($record->filters_json) ? $record->filters_json : [];
            $audience = $buildAudience->execute($request->user(), $filters);
            $executeCampaign->execute($record, $request->user(), $audience['recipients']);
        }

        return response()->json([
            'data' => [
                'id' => $record->id,
                'status' => $record->fresh()->status,
                'approvedAt' => $record->approved_at?->toIso8601String(),
            ],
        ]);
    }
}
