-- ═══════════════════════════════════════════════════════════════
-- SSO VietProDev — Seed: Default Users
-- Type: Data
-- Version: 2026-06-18
-- Purpose: Create default system admin, admin, and test users
--
-- This seed:
-- - Creates admin@vietprodev.com with system_admin role
-- - Creates admin@sso.vietprodev.com with admin role
-- - Creates test user with user role
-- - Uses bcrypt password hash (VietPro@2026)
-- - Idempotent: uses ON CONFLICT to handle re-runs
--
-- Dependencies: clean-migration.sql (auth schema), 100-seed-roles-permissions.sql
-- ═══════════════════════════════════════════════════════════════

-- Default password hash for: VietPro@2026
-- Generated with bcryptjs (cost factor: 12) on 2026-06-20
-- Verified to match exactly. If you want a different password, regenerate:
--   node -e "console.log(require('bcryptjs').hashSync('YourPassword', 12))"

-- ─────────────────────────────────────────────────────────────
-- Section 1: Create System Admin User
-- ─────────────────────────────────────────────────────────────

INSERT INTO users (id, email, username, first_name, last_name, status, created_at, updated_at)
SELECT
    gen_random_uuid() as id,
    'admin@vietprodev.com' as email,
    'sysadmin' as username,
    'System' as first_name,
    'Administrator' as last_name,
    'active' as status,
    CURRENT_TIMESTAMP as created_at,
    CURRENT_TIMESTAMP as updated_at
WHERE NOT EXISTS (
    SELECT 1 FROM users WHERE email = 'admin@vietprodev.com' OR username = 'sysadmin'
);

DO $$
DECLARE
    sysadmin_user_id UUID;
    sysadmin_role_id UUID;
BEGIN
    SELECT id INTO sysadmin_user_id FROM users WHERE email = 'admin@vietprodev.com' LIMIT 1;
    SELECT id INTO sysadmin_role_id FROM roles WHERE name = 'system_admin' LIMIT 1;

    IF sysadmin_user_id IS NOT NULL AND sysadmin_role_id IS NOT NULL THEN
        INSERT INTO user_auth (user_id, password_hash, password_changed_at, created_at, updated_at)
        VALUES (
            sysadmin_user_id,
            '$2b$12$zvxcUD87XNr1FFZKbF59iuYdL9vz4IbVm0vI1gBlYBng0CUSn8uzi', -- bcrypt hash of "VietPro@2026"
            CURRENT_TIMESTAMP,
            CURRENT_TIMESTAMP,
            CURRENT_TIMESTAMP
        )
        ON CONFLICT (user_id) DO NOTHING;

        UPDATE user_roles SET is_primary = FALSE, updated_at = CURRENT_TIMESTAMP
        WHERE user_id = sysadmin_user_id AND is_primary = TRUE;

        IF EXISTS (SELECT 1 FROM user_roles WHERE user_id = sysadmin_user_id AND role_id = sysadmin_role_id) THEN
            UPDATE user_roles
            SET is_primary = TRUE, updated_at = CURRENT_TIMESTAMP
            WHERE user_id = sysadmin_user_id AND role_id = sysadmin_role_id;
        ELSE
            INSERT INTO user_roles (user_id, role_id, assigned_at, assigned_by, is_primary, created_at, updated_at)
            VALUES (
                sysadmin_user_id,
                sysadmin_role_id,
                CURRENT_TIMESTAMP,
                sysadmin_user_id,
                TRUE,
                CURRENT_TIMESTAMP,
                CURRENT_TIMESTAMP
            );
        END IF;
    END IF;
END $$;

-- ─────────────────────────────────────────────────────────────
-- Section 2: Create Admin User
-- ─────────────────────────────────────────────────────────────

INSERT INTO users (id, email, username, first_name, last_name, status, created_at, updated_at)
SELECT
    gen_random_uuid() as id,
    'admin@sso.vietprodev.com' as email,
    'admin' as username,
    'SSO' as first_name,
    'Admin' as last_name,
    'active' as status,
    CURRENT_TIMESTAMP as created_at,
    CURRENT_TIMESTAMP as updated_at
WHERE NOT EXISTS (
    SELECT 1 FROM users WHERE email = 'admin@sso.vietprodev.com' OR username = 'admin'
);

DO $$
DECLARE
    admin_user_id UUID;
    admin_role_id UUID;
BEGIN
    SELECT id INTO admin_user_id FROM users WHERE email = 'admin@sso.vietprodev.com' LIMIT 1;
    SELECT id INTO admin_role_id FROM roles WHERE name = 'admin' LIMIT 1;

    IF admin_user_id IS NOT NULL AND admin_role_id IS NOT NULL THEN
        INSERT INTO user_auth (user_id, password_hash, password_changed_at, created_at, updated_at)
        VALUES (
            admin_user_id,
            '$2b$12$zvxcUD87XNr1FFZKbF59iuYdL9vz4IbVm0vI1gBlYBng0CUSn8uzi', -- bcrypt hash of "VietPro@2026"
            CURRENT_TIMESTAMP,
            CURRENT_TIMESTAMP,
            CURRENT_TIMESTAMP
        )
        ON CONFLICT (user_id) DO NOTHING;

        UPDATE user_roles SET is_primary = FALSE, updated_at = CURRENT_TIMESTAMP
        WHERE user_id = admin_user_id AND is_primary = TRUE;

        IF EXISTS (SELECT 1 FROM user_roles WHERE user_id = admin_user_id AND role_id = admin_role_id) THEN
            UPDATE user_roles
            SET is_primary = TRUE, updated_at = CURRENT_TIMESTAMP
            WHERE user_id = admin_user_id AND role_id = admin_role_id;
        ELSE
            INSERT INTO user_roles (user_id, role_id, assigned_at, assigned_by, is_primary, created_at, updated_at)
            VALUES (
                admin_user_id,
                admin_role_id,
                CURRENT_TIMESTAMP,
                admin_user_id,
                TRUE,
                CURRENT_TIMESTAMP,
                CURRENT_TIMESTAMP
            );
        END IF;
    END IF;
END $$;

-- ─────────────────────────────────────────────────────────────
-- Section 3: Create Test User
-- ─────────────────────────────────────────────────────────────

INSERT INTO users (id, email, username, first_name, last_name, status, created_at, updated_at)
SELECT
    gen_random_uuid() as id,
    'user@sso.vietprodev.com' as email,
    'testuser' as username,
    'Test' as first_name,
    'User' as last_name,
    'active' as status,
    CURRENT_TIMESTAMP as created_at,
    CURRENT_TIMESTAMP as updated_at
WHERE NOT EXISTS (
    SELECT 1 FROM users WHERE email = 'user@sso.vietprodev.com' OR username = 'testuser'
);

DO $$
DECLARE
    test_user_id UUID;
    user_role_id UUID;
BEGIN
    SELECT id INTO test_user_id FROM users WHERE email = 'user@sso.vietprodev.com' LIMIT 1;
    SELECT id INTO user_role_id FROM roles WHERE name = 'user' LIMIT 1;

    IF test_user_id IS NOT NULL AND user_role_id IS NOT NULL THEN
        INSERT INTO user_auth (user_id, password_hash, password_changed_at, created_at, updated_at)
        VALUES (
            test_user_id,
            '$2b$12$zvxcUD87XNr1FFZKbF59iuYdL9vz4IbVm0vI1gBlYBng0CUSn8uzi', -- bcrypt hash of "VietPro@2026"
            CURRENT_TIMESTAMP,
            CURRENT_TIMESTAMP,
            CURRENT_TIMESTAMP
        )
        ON CONFLICT (user_id) DO NOTHING;

        UPDATE user_roles SET is_primary = FALSE, updated_at = CURRENT_TIMESTAMP
        WHERE user_id = test_user_id AND is_primary = TRUE;

        IF EXISTS (SELECT 1 FROM user_roles WHERE user_id = test_user_id AND role_id = user_role_id) THEN
            UPDATE user_roles
            SET is_primary = TRUE, updated_at = CURRENT_TIMESTAMP
            WHERE user_id = test_user_id AND role_id = user_role_id;
        ELSE
            INSERT INTO user_roles (user_id, role_id, assigned_at, assigned_by, is_primary, created_at, updated_at)
            VALUES (
                test_user_id,
                user_role_id,
                CURRENT_TIMESTAMP,
                test_user_id,
                TRUE,
                CURRENT_TIMESTAMP,
                CURRENT_TIMESTAMP
            );
        END IF;
    END IF;
END $$;

-- ═══════════════════════════════════════════════════════════════
-- End of Seed
-- ═══════════════════════════════════════════════════════════════
-- Default credentials (CHANGE IN PRODUCTION):
--   System Admin: admin@vietprodev.com      / VietPro@2026
--   Admin:        admin@sso.vietprodev.com  / VietPro@2026
--   User:         user@sso.vietprodev.com   / VietPro@2026
-- ═══════════════════════════════════════════════════════════════