<?php

namespace App\Domains\Tasks\Actions;

use App\Domains\Conversations\Models\Conversation;
use App\Domains\Leads\Models\Lead;
use App\Domains\Orders\Models\Order;
use App\Domains\Tasks\Models\Task;
use App\Domains\Tenancy\Models\Branch;
use App\Domains\Tenancy\Models\Tenant;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class SeedDemoTasksAction
{
    public function execute(Tenant $tenant, User $owner, Branch $branch): void
    {
        DB::transaction(function () use ($tenant, $owner, $branch) {
            if (Task::query()->where('tenant_id', $tenant->getKey())->exists()) {
                return;
            }

            $conversation = Conversation::query()->where('tenant_id', $tenant->getKey())->first();
            $lead = Lead::query()->where('tenant_id', $tenant->getKey())->first();
            $order = Order::query()->where('tenant_id', $tenant->getKey())->first();

            $tasks = [
                [
                    'title' => 'Follow up on perfume inquiry',
                    'description' => 'Check if customer is still interested and offer delivery details.',
                    'priority' => 'high',
                    'due_at' => now()->addHours(6),
                    'conversation_id' => $conversation?->getKey(),
                    'contact_id' => $conversation?->contact_id,
                    'lead_id' => $lead?->getKey(),
                ],
                [
                    'title' => 'Review wholesale quote response',
                    'description' => 'Call customer if no answer by tomorrow morning.',
                    'priority' => 'medium',
                    'due_at' => now()->addDay(),
                    'lead_id' => Lead::query()->where('tenant_id', $tenant->getKey())->orderByDesc('estimated_value')->first()?->getKey(),
                ],
                [
                    'title' => 'Collect remaining order payment',
                    'description' => 'Coordinate second installment for confirmed wholesale order.',
                    'priority' => 'high',
                    'due_at' => now()->subHours(4),
                    'order_id' => $order?->getKey(),
                    'contact_id' => $order?->contact_id,
                ],
            ];

            foreach ($tasks as $task) {
                Task::query()->create([
                    'tenant_id' => $tenant->getKey(),
                    'branch_id' => $branch->getKey(),
                    'assigned_user_id' => $owner->getKey(),
                    'created_by' => $owner->getKey(),
                    'status' => 'open',
                    ...$task,
                ]);
            }
        });
    }
}
