-- ═══════════════════════════════════════════════════════════════
-- Seed: Default Users
-- Type: Data
-- Version: 2026-05-02
-- Purpose: Create default system admin, admin, and test users
--
-- This seed:
-- - Creates admin@meu-solutions.com with system_admin role
-- - Creates admin@bekind.com with admin role
-- - Creates test user with user role
-- - Uses bcrypt password hash (Meu@2026)
-- - Idempotent: uses ON CONFLICT to handle re-runs
--
-- Dependencies: 001-auth-schema.sql, 100-seed-roles-permissions.sql
-- ═══════════════════════════════════════════════════════════════

-- Default password hash for: Meu@2026
-- Generated with bcrypt (cost factor: 12)
-- If you want to use a different password, update this hash
-- or use the JavaScript seed script instead

-- ─────────────────────────────────────────────────────────────
-- Section 1: 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@bekind.com' as email,
    'admin' 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@bekind.com' OR username = 'admin'
);

-- Get admin user id and assign role
DO $$
DECLARE
    admin_user_id UUID;
    admin_role_id UUID;
BEGIN
    SELECT id INTO admin_user_id FROM users WHERE email = 'admin@bekind.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 user_auth for admin (password: Meu@2026)
        INSERT INTO user_auth (user_id, password_hash, password_changed_at, created_at, updated_at)
        VALUES (
            admin_user_id,
            '$2b$12$RVqgGfwkSCPMxxiBgQUweuRatXSfVvHZLSZOjEUxUJ7Y4RVvGd4rm', -- bcrypt hash of "Meu@2026"
            CURRENT_TIMESTAMP,
            CURRENT_TIMESTAMP,
            CURRENT_TIMESTAMP
        )
        ON CONFLICT (user_id) DO NOTHING;
        
        -- Assign admin role to admin
        -- First, set any existing primary role to FALSE for this user
        UPDATE user_roles SET is_primary = FALSE, updated_at = CURRENT_TIMESTAMP
        WHERE user_id = admin_user_id AND is_primary = TRUE;

        -- Check if user already has this role
        IF EXISTS (SELECT 1 FROM user_roles WHERE user_id = admin_user_id AND role_id = admin_role_id) THEN
            -- Update existing role to set as primary
            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 new role as primary
            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 2: 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@bekind.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@bekind.com' OR username = 'testuser'
);

-- Get test user id and assign role
DO $$
DECLARE
    test_user_id UUID;
    user_role_id UUID;
BEGIN
    SELECT id INTO test_user_id FROM users WHERE email = 'user@bekind.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 user_auth for test user (password: Meu@2026)
        INSERT INTO user_auth (user_id, password_hash, password_changed_at, created_at, updated_at)
        VALUES (
            test_user_id,
            '$2b$12$RVqgGfwkSCPMxxiBgQUweuRatXSfVvHZLSZOjEUxUJ7Y4RVvGd4rm', -- bcrypt hash of "Meu@2026"
            CURRENT_TIMESTAMP,
            CURRENT_TIMESTAMP,
            CURRENT_TIMESTAMP
        )
        ON CONFLICT (user_id) DO NOTHING;
        
        -- Assign user role to test user
        -- First, set any existing primary role to FALSE for this user
        UPDATE user_roles SET is_primary = FALSE, updated_at = CURRENT_TIMESTAMP
        WHERE user_id = test_user_id AND is_primary = TRUE;

        -- Check if user already has this role
        IF EXISTS (SELECT 1 FROM user_roles WHERE user_id = test_user_id AND role_id = user_role_id) THEN
            -- Update existing role to set as primary
            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 new role as primary
            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 $$;

-- ─────────────────────────────────────────────────────────────
-- Section 3: Create MEU Solutions System Admin
-- ─────────────────────────────────────────────────────────────

INSERT INTO users (id, email, username, first_name, last_name, status, created_at, updated_at)
SELECT
    gen_random_uuid() as id,
    'admin@meu-solutions.com' as email,
    'meu_admin' as username,
    'MEU' as first_name,
    'Solutions' 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@meu-solutions.com' OR username = 'meu_admin'
);

-- Get MEU admin id and assign role
DO $$
DECLARE
    meu_admin_id UUID;
    system_admin_role_id UUID;
BEGIN
    SELECT id INTO meu_admin_id FROM users WHERE email = 'admin@meu-solutions.com' LIMIT 1;
    SELECT id INTO system_admin_role_id FROM roles WHERE name = 'system_admin' LIMIT 1;

    IF meu_admin_id IS NOT NULL AND system_admin_role_id IS NOT NULL THEN
        -- Insert user_auth for meu admin (password: Meu@2026)
        INSERT INTO user_auth (user_id, password_hash, password_changed_at, created_at, updated_at)
        VALUES (
            meu_admin_id,
            '$2b$12$RVqgGfwkSCPMxxiBgQUweuRatXSfVvHZLSZOjEUxUJ7Y4RVvGd4rm', -- bcrypt hash of "Meu@2026"
            CURRENT_TIMESTAMP,
            CURRENT_TIMESTAMP,
            CURRENT_TIMESTAMP
        )
        ON CONFLICT (user_id) DO NOTHING;

        -- Assign system_admin role
        -- First, set any existing primary role to FALSE for this user
        UPDATE user_roles SET is_primary = FALSE, updated_at = CURRENT_TIMESTAMP
        WHERE user_id = meu_admin_id AND is_primary = TRUE;

        -- Check if user already has this role
        IF EXISTS (SELECT 1 FROM user_roles WHERE user_id = meu_admin_id AND role_id = system_admin_role_id) THEN
            -- Update existing role to set as primary
            UPDATE user_roles
            SET is_primary = TRUE, updated_at = CURRENT_TIMESTAMP
            WHERE user_id = meu_admin_id AND role_id = system_admin_role_id;
        ELSE
            -- Insert new role as primary
            INSERT INTO user_roles (user_id, role_id, assigned_at, assigned_by, is_primary, created_at, updated_at)
            VALUES (
                meu_admin_id,
                system_admin_role_id,
                CURRENT_TIMESTAMP,
                meu_admin_id,
                TRUE,
                CURRENT_TIMESTAMP,
                CURRENT_TIMESTAMP
            );
        END IF;
    END IF;
END $$;

-- ═══════════════════════════════════════════════════════════════
-- End of Seed
-- ═══════════════════════════════════════════════════════════════
-- Default credentials:
--   System Admin: admin@meu-solutions.com / Meu@2026
--   Admin:        admin@bekind.com        / Meu@2026
--   User:         user@bekind.com         / Meu@2026
