<?php

define('ROOT_PATH', dirname(__DIR__));
require_once ROOT_PATH . '/app/core/Autoloader.php';
\App\Core\Autoloader::register();

$bootstrap = new \App\Core\Bootstrap();
$bootstrap->init();

use App\Core\Database;
use App\Modules\Workspace\WorkspaceService;

try {
    $db = Database::getConnection();
    
    echo "Seeding default users...\n";
    
    // 1. Seed Super Admin
    // Password: admin / admin (BETA-001 acceptance credential)
    $adminPasswordHash = password_hash('admin', PASSWORD_DEFAULT);
    $stmt = $db->prepare("SELECT id FROM users WHERE role_id = 1 LIMIT 1");
    $stmt->execute();
    $admin = $stmt->fetch();
    
    if (!$admin) {
        $stmt = $db->prepare("
            INSERT INTO users (role_id, email, username, display_name, password_hash, is_active, workspace_id)
            VALUES (1, 'admin@inveetaire.local', 'admin', 'Super Admin', ?, 1, NULL)
        ");
        $stmt->execute([$adminPasswordHash]);
        $adminId = (int) $db->lastInsertId();
        echo "Created Super Admin user (ID: $adminId)\n";
    } else {
        $adminId = (int) $admin['id'];
        $stmt = $db->prepare("
            UPDATE users 
               SET email = 'admin@inveetaire.local', 
                   username = 'admin', 
                   display_name = 'Super Admin', 
                   password_hash = ?, 
                   is_active = 1
             WHERE id = ?
        ");
        $stmt->execute([$adminPasswordHash, $adminId]);
        echo "Updated Super Admin user (ID: $adminId)\n";
    }
    
    // 2. Seed Crew
    // Password: crew / admin (operational credential)
    $crewPasswordHash = password_hash('admin', PASSWORD_DEFAULT);
    $stmt = $db->prepare("SELECT id FROM users WHERE role_id = 3 LIMIT 1");
    $stmt->execute();
    $crew = $stmt->fetch();
    
    if (!$crew) {
        $stmt = $db->prepare("
            INSERT INTO users (role_id, email, username, display_name, password_hash, is_active, workspace_id)
            VALUES (3, 'crew@inveetaire.local', 'crew', 'Crew', ?, 1, NULL)
        ");
        $stmt->execute([$crewPasswordHash]);
        $crewId = (int) $db->lastInsertId();
        echo "Created Crew user (ID: $crewId)\n";
    } else {
        $crewId = (int) $crew['id'];
        $stmt = $db->prepare("
            UPDATE users 
               SET email = 'crew@inveetaire.local', 
                   username = 'crew', 
                   display_name = 'Crew', 
                   password_hash = ?, 
                   is_active = 1
             WHERE id = ?
        ");
        $stmt->execute([$crewPasswordHash, $crewId]);
        echo "Updated Crew user (ID: $crewId)\n";
    }
    
    // 3. Seed Test Couple & Workspace
    $stmt = $db->prepare("SELECT id FROM workspaces WHERE slug = 'test-couple' LIMIT 1");
    $stmt->execute();
    $workspace = $stmt->fetch();
    
    if (!$workspace) {
        echo "Workspace 'test-couple' does not exist. Provisioning via WorkspaceService...\n";
        $service = new WorkspaceService();
        $provisionResult = $service->provision([
            'slug'               => 'test-couple',
            'groom_name'         => 'Test Groom',
            'bride_name'         => 'Test Bride',
            'wedding_date'       => '2026-12-31',
            'event_type_id'      => 1,
            'commercial_plan_id' => 2
        ], $adminId, '127.0.0.1');
        
        $workspaceId = (int) $provisionResult['workspace_id'];
        $coupleUserId = (int) $provisionResult['user_id'];
        echo "Provisioned workspace 'test-couple' (ID: $workspaceId, Couple User ID: $coupleUserId)\n";
    } else {
        $workspaceId = (int) $workspace['id'];
        echo "Workspace 'test-couple' already exists (ID: $workspaceId)\n";
        
        // Find existing couple user for this workspace
        $stmt = $db->prepare("SELECT id FROM users WHERE role_id = 2 AND workspace_id = ? LIMIT 1");
        $stmt->execute([$workspaceId]);
        $coupleUser = $stmt->fetch();
        
        if (!$coupleUser) {
            $stmt = $db->prepare("
                INSERT INTO users (role_id, email, username, display_name, password_hash, is_active, workspace_id)
                VALUES (2, 'test@inveetaire.local', 'test', 'Test Couple', '', 1, ?)
            ");
            $stmt->execute([$workspaceId]);
            $coupleUserId = (int) $db->lastInsertId();
            echo "Created Couple user for existing workspace (ID: $coupleUserId)\n";
        } else {
            $coupleUserId = (int) $coupleUser['id'];
        }
    }
    
    // Update Test Couple credentials
    // Password: test / test (BETA-001 acceptance credential)
    $couplePasswordHash = password_hash('test', PASSWORD_DEFAULT);
    $stmt = $db->prepare("
        UPDATE users
           SET email = 'test@inveetaire.local',
               username = 'test',
               display_name = 'Test Couple',
               password_hash = ?,
               is_active = 1
         WHERE id = ?
    ");
    $stmt->execute([$couplePasswordHash, $coupleUserId]);
    echo "Updated Test Couple credentials (User ID: $coupleUserId)\n";

    // Re-enforce Super Admin password to prevent cross-contamination from
    // prior seed runs. Admin must always authenticate as admin/admin.
    $stmt = $db->prepare("
        UPDATE users
           SET password_hash = ?
         WHERE id = ?
    ");
    $stmt->execute([$adminPasswordHash, $adminId]);
    // 4. Developer Sandbox Accounts (local/debug only)
    $isDev = (env('APP_ENV', 'local') === 'local') || (bool)env('APP_DEBUG', false);
    if ($isDev) {
        echo "Development environment detected. Seeding developer sandbox accounts...\n";
        
        // Ensure default developer workspace exists
        $devWorkspaceSlug = 'test-couple-workspace';
        $stmt = $db->prepare("SELECT id FROM workspaces WHERE slug = ? LIMIT 1");
        $stmt->execute([$devWorkspaceSlug]);
        $devWorkspace = $stmt->fetch();
        
        if (!$devWorkspace) {
            echo "Provisioning default development workspace 'Test Couple Workspace'...\n";
            $service = new WorkspaceService();
            $provisionResult = $service->provision([
                'slug'               => $devWorkspaceSlug,
                'groom_name'         => 'Dev Groom',
                'bride_name'         => 'Dev Bride',
                'wedding_date'       => '2027-12-31',
                'event_type_id'      => 1,
                'commercial_plan_id' => 2
            ], $adminId, '127.0.0.1');
            
            $devWorkspaceId = (int) $provisionResult['workspace_id'];
            echo "Created development workspace 'Test Couple Workspace' (ID: $devWorkspaceId)\n";
        } else {
            $devWorkspaceId = (int) $devWorkspace['id'];
            echo "Development workspace 'Test Couple Workspace' already exists (ID: $devWorkspaceId)\n";
        }
        
        $sandboxPasswordHash = password_hash('Test@123', PASSWORD_DEFAULT);
        
        // A. Super Admin (testsuperadmin)
        $stmt = $db->prepare("SELECT id FROM users WHERE username = 'testsuperadmin' LIMIT 1");
        $stmt->execute();
        $sandboxAdmin = $stmt->fetch();
        if (!$sandboxAdmin) {
            $stmt = $db->prepare("
                INSERT INTO users (role_id, email, username, display_name, password_hash, is_active, workspace_id)
                VALUES (1, 'testsuperadmin@inveetaire.local', 'testsuperadmin', 'Test Super Admin', ?, 1, NULL)
            ");
            $stmt->execute([$sandboxPasswordHash]);
            echo "Created developer Super Admin (testsuperadmin)\n";
        } else {
            $stmt = $db->prepare("
                UPDATE users 
                   SET email = 'testsuperadmin@inveetaire.local', 
                       display_name = 'Test Super Admin', 
                       password_hash = ?, 
                       is_active = 1 
                 WHERE id = ?
            ");
            $stmt->execute([$sandboxPasswordHash, (int) $sandboxAdmin['id']]);
            echo "Updated developer Super Admin (testsuperadmin)\n";
        }
        
        // B. Couple (testcouple)
        $stmt = $db->prepare("SELECT id FROM users WHERE username = 'testcouple' LIMIT 1");
        $stmt->execute();
        $sandboxCouple = $stmt->fetch();
        if (!$sandboxCouple) {
            $stmt = $db->prepare("
                INSERT INTO users (role_id, email, username, display_name, password_hash, is_active, workspace_id)
                VALUES (2, 'testcouple@inveetaire.local', 'testcouple', 'Test Couple User', ?, 1, ?)
            ");
            $stmt->execute([$sandboxPasswordHash, $devWorkspaceId]);
            echo "Created developer Couple (testcouple)\n";
        } else {
            $stmt = $db->prepare("
                UPDATE users 
                   SET email = 'testcouple@inveetaire.local', 
                       display_name = 'Test Couple User', 
                       password_hash = ?, 
                       is_active = 1,
                       workspace_id = ?
                 WHERE id = ?
            ");
            $stmt->execute([$sandboxPasswordHash, $devWorkspaceId, (int) $sandboxCouple['id']]);
            echo "Updated developer Couple (testcouple)\n";
        }
        
        // C. Crew (testcrew)
        $stmt = $db->prepare("SELECT id FROM users WHERE username = 'testcrew' LIMIT 1");
        $stmt->execute();
        $sandboxCrew = $stmt->fetch();
        if (!$sandboxCrew) {
            $stmt = $db->prepare("
                INSERT INTO users (role_id, email, username, display_name, password_hash, is_active, workspace_id)
                VALUES (3, 'testcrew@inveetaire.local', 'testcrew', 'Test Crew User', ?, 1, ?)
            ");
            $stmt->execute([$sandboxPasswordHash, $devWorkspaceId]);
            echo "Created developer Crew (testcrew)\n";
        } else {
            $stmt = $db->prepare("
                UPDATE users 
                   SET email = 'testcrew@inveetaire.local', 
                       display_name = 'Test Crew User', 
                       password_hash = ?, 
                       is_active = 1,
                       workspace_id = ?
                 WHERE id = ?
            ");
            $stmt->execute([$sandboxPasswordHash, $devWorkspaceId, (int) $sandboxCrew['id']]);
            echo "Updated developer Crew (testcrew)\n";
        }

        // D. Seed Crew Assignments (many-to-many)
        $stmt = $db->prepare("SELECT id FROM users WHERE username = 'testcrew' LIMIT 1");
        $stmt->execute();
        $crewUserVal = $stmt->fetch();
        $crewUserId = $crewUserVal ? (int) $crewUserVal['id'] : 0;

        $stmt = $db->prepare("SELECT id FROM workspaces WHERE slug = 'test-couple' LIMIT 1");
        $stmt->execute();
        $ws1 = $stmt->fetch();
        $ws1Id = $ws1 ? (int) $ws1['id'] : 0;

        $stmt = $db->prepare("SELECT id FROM workspaces WHERE slug = 'test-couple-workspace' LIMIT 1");
        $stmt->execute();
        $ws2 = $stmt->fetch();
        $ws2Id = $ws2 ? (int) $ws2['id'] : 0;

        if ($crewUserId > 0) {
            if ($ws1Id > 0) {
                $stmt = $db->prepare("INSERT INTO crew_accounts (workspace_id, user_id, display_name, desk_label, is_active) VALUES (?, ?, 'Test Crew A', 'Desk A', 1) ON DUPLICATE KEY UPDATE is_active = 1");
                $stmt->execute([$ws1Id, $crewUserId]);
                echo "Assigned testcrew to workspace 'test-couple' (ID: $ws1Id)\n";
            }
            if ($ws2Id > 0) {
                $stmt = $db->prepare("INSERT INTO crew_accounts (workspace_id, user_id, display_name, desk_label, is_active) VALUES (?, ?, 'Test Crew B', 'Desk B', 1) ON DUPLICATE KEY UPDATE is_active = 1");
                $stmt->execute([$ws2Id, $crewUserId]);
                echo "Assigned testcrew to workspace 'test-couple-workspace' (ID: $ws2Id)\n";
            }
        }
    }
    
    echo "Seeding completed successfully!\n";
    
} catch (\Throwable $e) {
    echo "ERROR: " . $e->getMessage() . "\n";
    echo $e->getTraceAsString() . "\n";
}
