<?php

declare(strict_types=1);

namespace ImovelZapAi\Organizations\Application\Actions;

use App\Models\User;
use ImovelZapAi\Tenancy\Infrastructure\Persistence\Eloquent\TenantModel;

final class SetOrganizationOwnerAction
{
    public function execute(string $tenantId, string $userId): TenantModel
    {
        $tenant = TenantModel::query()->findOrFail($tenantId);

        User::query()
            ->where('tenant_id', $tenantId)
            ->whereKey($userId)
            ->firstOrFail();

        $tenant->forceFill(['owner_user_id' => $userId])->save();

        return $tenant->fresh() ?? $tenant;
    }
}
