<?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 FollowUpCampaignSendController extends Controller
{
    public function __invoke(
        Request $request,
        BuildFollowUpCampaignAudienceAction $buildAudience,
        ExecuteFollowUpCampaignAction $executeCampaign
    ): JsonResponse {
        $validated = $request->validate([
            'confirm' => ['required', 'accepted'],
            'message_template' => ['required', 'string', 'min:10', 'max:1200'],
            'filters' => ['required', 'array'],
            'filters.conditions' => ['required', 'array', 'min:1'],
            'filters.conditions.*' => ['string'],
            'filters.channel' => ['nullable', 'in:all,whatsapp,instagram'],
            'filters.inactive_days' => ['nullable', 'integer', 'min:30', 'max:365'],
            'filters.no_purchase_days' => ['nullable', 'integer', 'min:1', 'max:90'],
            'filters.unread_hours' => ['nullable', 'integer', 'min:1', 'max:72'],
            'filters.cooldown_hours' => ['nullable', 'integer', 'min:0', 'max:720'],
            'filters.max_touches_30_days' => ['nullable', 'integer', 'min:0', 'max:20'],
            'filters.limit' => ['nullable', 'integer', 'min:1', 'max:500'],
            'recipient_ids' => ['nullable', 'array'],
            'recipient_ids.*' => ['string'],
        ]);

        $audience = $buildAudience->execute($request->user(), $validated['filters']);
        $recipients = $audience['recipients'];

        if (! empty($validated['recipient_ids'])) {
            $allow = array_flip($validated['recipient_ids']);
            $recipients = array_values(array_filter(
                $recipients,
                static fn (array $row): bool => isset($allow[$row['contactId'] ?? ''])
            ));
        }

        if (count($recipients) === 0) {
            return response()->json([
                'message' => 'No recipients match current conditions.',
            ], 422);
        }

        $campaign = FollowUpCampaign::query()->create([
            'tenant_id' => $request->user()->tenant_id,
            'name' => 'Manual Campaign '.now()->format('Y-m-d H:i'),
            'status' => 'draft',
            'channel' => $validated['filters']['channel'] ?? 'all',
            'filters_json' => $audience['applied'],
            'guardrails_json' => [
                'cooldown_hours' => (int) ($audience['applied']['cooldown_hours'] ?? 72),
                'max_touches_30_days' => (int) ($audience['applied']['max_touches_30_days'] ?? 3),
            ],
            'message_template' => (string) $validated['message_template'],
            'is_auto_enabled' => false,
            'requires_approval' => false,
            'created_by' => $request->user()->getKey(),
        ]);

        $result = $executeCampaign->execute($campaign, $request->user(), $recipients);

        return response()->json([
            'data' => [
                'sent' => $result['sent'],
                'skipped' => $result['skipped'],
                'sample' => $result['details'],
                'campaignId' => $campaign->id,
                'filters' => $audience['applied'],
            ],
        ], 201);
    }
}
