<?php

namespace Database\Factories;

use App\Models\ProviderConnection;
use App\Models\Tenant;
use App\Models\Workspace;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends Factory<ProviderConnection>
 */
class ProviderConnectionFactory extends Factory
{
    protected $model = ProviderConnection::class;

    public function definition(): array
    {
        return [
            'tenant_id' => Tenant::factory()->for(Workspace::factory()),
            'workspace_id' => function (array $attributes): int {
                $tenantId = $attributes['tenant_id'] ?? null;

                if (! is_numeric($tenantId)) {
                    return (int) Workspace::factory()->create()->getKey();
                }

                $tenant = Tenant::query()->whereKey((int) $tenantId)->first();

                if (! $tenant instanceof Tenant) {
                    return (int) Workspace::factory()->create()->getKey();
                }

                if ($tenant->workspace_id === null) {
                    $workspaceId = (int) Workspace::factory()->create()->getKey();
                    $tenant->forceFill(['workspace_id' => $workspaceId])->save();

                    return $workspaceId;
                }

                return (int) $tenant->workspace_id;
            },
            'provider' => 'microsoft',
            'entra_tenant_id' => fake()->uuid(),
            'display_name' => fake()->company(),
            'is_default' => false,
            'status' => 'needs_consent',
            'health_status' => 'unknown',
            'scopes_granted' => [],
            'last_health_check_at' => null,
            'last_error_reason_code' => null,
            'last_error_message' => null,
            'metadata' => [],
        ];
    }
}
