<?php

namespace Database\Seeders;

use App\Models\ActivityLog;
use App\Models\Agent;
use App\Models\ApiAgentLog;
use App\Models\Backup;
use App\Models\LoginHistory;
use App\Models\SiteHealthLog;
use App\Models\SystemSetting;
use App\Models\TableSnapshot;
use App\Models\User;
use App\Models\Website;
use App\Support\LocalHarnessManager;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        $admin = User::query()->updateOrCreate(
            ['email' => 'arafatcontrol@gmail.com'],
            [
                'name' => 'Arafat Control',
                'is_super_admin' => true,
                'password' => 'Contron11@@123',
            ],
        );

        LoginHistory::factory(4)->for($admin)->create();

        $settings = [
            ['group' => 'General', 'key' => 'company_name', 'label' => 'Platform Name', 'type' => 'text', 'value' => 'Central Control Center', 'description' => 'Displayed in the top bar and browser title.'],
            ['group' => 'Security', 'key' => 'emergency_lock_mode', 'label' => 'Emergency Lock Mode', 'type' => 'boolean', 'value' => '0', 'description' => 'Temporarily block new logins while maintenance is in progress.'],
            ['group' => 'Theme', 'key' => 'default_theme', 'label' => 'Default Theme', 'type' => 'text', 'value' => 'dark', 'description' => 'Applied before the local browser preference takes over.'],
            ['group' => 'Notifications', 'key' => 'alert_email', 'label' => 'Alert Email', 'type' => 'text', 'value' => 'alerts@control-center.test', 'description' => 'Receives backup failures and agent health warnings.'],
            ['group' => 'API', 'key' => 'agent_timeout', 'label' => 'Agent Timeout (seconds)', 'type' => 'number', 'value' => '5', 'description' => 'Timeout for remote agent health and metadata requests.'],
            ['group' => 'Backup', 'key' => 'retention_days', 'label' => 'Backup Retention (days)', 'type' => 'number', 'value' => '30', 'description' => 'How long completed backups should be kept by default.'],
        ];

        foreach ($settings as $setting) {
            SystemSetting::query()->updateOrCreate(['key' => $setting['key']], $setting);
        }

        $profiles = [
            ['name' => 'Northwind Commerce', 'domain' => 'northwind.example.com', 'status' => 'online', 'health_status' => 'healthy'],
            ['name' => 'Aster Media', 'domain' => 'aster.example.net', 'status' => 'online', 'health_status' => 'healthy'],
            ['name' => 'Crescent Travel', 'domain' => 'crescent.example.org', 'status' => 'degraded', 'health_status' => 'warning'],
            ['name' => 'Harbor Schools', 'domain' => 'harbor.example.edu', 'status' => 'offline', 'health_status' => 'critical'],
            ['name' => 'Pioneer Labs', 'domain' => 'pioneer.example.io', 'status' => 'disabled', 'health_status' => 'unknown'],
            ['name' => 'Summit Foods', 'domain' => 'summit.example.co', 'status' => 'pending', 'health_status' => 'warning'],
        ];

        foreach ($profiles as $index => $profile) {
            $website = Website::factory()->for($admin, 'createdBy')->create([
                'name' => $profile['name'],
                'domain' => $profile['domain'],
                'connection_type' => 'api_agent',
                'api_endpoint' => 'https://'.$profile['domain'].'/agent',
                'status' => $profile['status'],
                'health_status' => $profile['health_status'],
                'database_count' => fake()->numberBetween(1, 4),
                'table_count' => fake()->numberBetween(18, 96),
                'response_time_ms' => $profile['status'] === 'offline' ? 1600 : fake()->numberBetween(90, 420),
                'last_seen_at' => now()->subMinutes($index * 12 + 4),
                'last_synced_at' => now()->subMinutes($index * 15 + 8),
            ]);

            Agent::factory()->for($website)->create([
                'status' => $profile['status'] === 'disabled' ? 'offline' : $profile['status'],
                'authentication_status' => $profile['status'] === 'offline' ? 'expired' : 'verified',
                'sync_status' => in_array($profile['status'], ['online', 'degraded'], true) ? 'synced' : 'stale',
                'latency_ms' => $profile['status'] === 'offline' ? 1800 : fake()->numberBetween(80, 450),
                'capabilities' => ['health', 'tables', 'table-structure', 'backups'],
            ]);

            TableSnapshot::factory(fake()->numberBetween(4, 8))->for($website)->create();
            Backup::factory(fake()->numberBetween(2, 4))->for($website)->for($admin, 'initiatedBy')->create();
            ActivityLog::factory(fake()->numberBetween(5, 9))->for($website)->for($admin)->create();

            SiteHealthLog::query()->create([
                'website_id' => $website->id,
                'status' => $website->status,
                'health_status' => $website->health_status,
                'response_time_ms' => $website->response_time_ms,
                'message' => $website->status === 'online'
                    ? 'Seeded health check completed successfully.'
                    : 'Seeded health check flagged this website for review.',
                'payload' => [
                    'seeded' => true,
                    'database_count' => $website->database_count,
                    'table_count' => $website->table_count,
                ],
                'checked_at' => $website->last_seen_at ?? now(),
            ]);

            ApiAgentLog::query()->create([
                'website_id' => $website->id,
                'agent_id' => $website->agent?->id,
                'direction' => 'outbound',
                'method' => 'GET',
                'endpoint' => rtrim($website->api_endpoint, '/').'/health',
                'http_status' => $website->status === 'offline' ? 503 : 200,
                'latency_ms' => $website->response_time_ms,
                'was_successful' => $website->status !== 'offline',
                'message' => $website->status === 'offline'
                    ? 'Seeded connectivity check failed.'
                    : 'Seeded connectivity check succeeded.',
                'request_headers' => ['Accept' => 'application/json'],
                'request_payload' => [],
                'response_headers' => [],
                'response_body' => [
                    'status' => $website->status,
                    'health' => $website->health_status,
                ],
                'logged_at' => $website->last_synced_at ?? now(),
            ]);
        }

        app(LocalHarnessManager::class)->provision($admin);

        ActivityLog::query()->create([
            'user_id' => $admin->id,
            'category' => 'auth',
            'action' => 'login.success',
            'description' => 'Initial super admin account seeded for local development access.',
            'ip_address' => '127.0.0.1',
            'user_agent' => 'Seeder',
            'meta' => ['seeded' => true],
            'occurred_at' => now(),
        ]);

        User::factory(2)->create();
    }
}
