<?php

namespace App\Domains\Tasks\Actions;

use App\Domains\Conversations\Models\Conversation;
use App\Domains\Conversations\Models\Message;
use App\Models\User;
use Illuminate\Support\Arr;

class SendFollowUpCampaignAction
{
    /**
     * @param array<int, array<string, mixed>> $recipients
     * @return array{sent:int,skipped:int,details:array<int,array<string,mixed>>}
     */
    public function execute(User $user, array $recipients, string $template): array
    {
        $sent = 0;
        $skipped = 0;
        $details = [];

        foreach ($recipients as $recipient) {
            $conversationId = (string) ($recipient['conversationId'] ?? '');
            $name = (string) ($recipient['name'] ?? 'there');
            if ($conversationId === '') {
                $skipped++;
                continue;
            }

            $conversation = Conversation::query()
                ->where('tenant_id', $user->tenant_id)
                ->find($conversationId);

            if (! $conversation) {
                $skipped++;
                continue;
            }

            $body = str_replace(
                ['{name}', '{company}'],
                [$name, $user->tenant?->company_name ?? 'our store'],
                $template
            );

            Message::query()->create([
                'tenant_id' => $user->tenant_id,
                'conversation_id' => $conversation->getKey(),
                'direction' => 'outbound',
                'message_type' => 'text',
                'body_text' => $body,
                'sent_by_user_id' => $user->getKey(),
                'sent_at' => now(),
                'created_at' => now(),
            ]);

            $conversation->update([
                'first_response_at' => $conversation->first_response_at ?? now(),
                'last_message_at' => now(),
                'unread_count' => 0,
                'status' => 'open',
            ]);

            $sent++;
            if (count($details) < 20) {
                $details[] = [
                    'contactId' => Arr::get($recipient, 'contactId'),
                    'name' => $name,
                    'channel' => Arr::get($recipient, 'channel'),
                ];
            }
        }

        return [
            'sent' => $sent,
            'skipped' => $skipped,
            'details' => $details,
        ];
    }
}
