<?php

declare(strict_types=1);

namespace ImovelZapAi\Conversations\Application\Actions;

use ImovelZapAi\Conversations\Domain\Enums\ConversationStatus;
use ImovelZapAi\Conversations\Domain\Enums\HandoffStatus;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ConversationModel;
use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\HumanHandoffModel;
use ImovelZapAi\Properties\Domain\Enums\PropertyInterestStatus;
use ImovelZapAi\Properties\Infrastructure\Persistence\Eloquent\PropertyInterestModel;
use ImovelZapAi\Tenancy\Support\TenantContext;
use ImovelZapAi\Users\Infrastructure\Persistence\Eloquent\UserModel;

final class ClaimHandoffAction
{
    public function execute(string $tenantId, HumanHandoffModel $handoff, UserModel $user): HumanHandoffModel
    {
        TenantContext::set($tenantId);

        if ($handoff->status !== HandoffStatus::Waiting) {
            return $handoff;
        }

        $handoff->update([
            'status' => HandoffStatus::Claimed,
            'assigned_user_id' => $user->id,
            'claimed_at' => now(),
        ]);

        PropertyInterestModel::query()
            ->where('tenant_id', $tenantId)
            ->where('contact_id', $handoff->contact_id)
            ->where('conversation_id', $handoff->conversation_id)
            ->get()
            ->each(function (PropertyInterestModel $interest) use ($user): void {
                if ($interest->status?->canTransitionTo(PropertyInterestStatus::InProgress) ?? false) {
                    $interest->update([
                        'status' => PropertyInterestStatus::InProgress,
                        'assigned_user_id' => $user->id,
                    ]);
                }
            });

        ConversationModel::query()
            ->whereKey($handoff->conversation_id)
            ->update([
                'status' => ConversationStatus::Negotiating,
            ]);

        return $handoff->fresh(['contact', 'summary', 'leadScore']) ?? $handoff;
    }
}
