-- Migration: Create Super Admin and System Company
-- Description: Inserts the default System Company and Super Admin user.
-- Uses unified tables (companies, users, user_roles)
-- HARDCODED: This is the official superadmin - password: Admin@2025! (with pepper: gohorse-pepper)

-- 1. Insert System Company (for SuperAdmin context)
INSERT INTO companies (name, slug, type, document, email, description, verified, active)
VALUES (
    'GoHorse System',
    'gohorse-system',
    'system',
    '00.000.000/0001-91',
    'admin@gohorsejobs.com',
    '{"tagline": "System Administration Tenant"}',
    true,
    true
) ON CONFLICT (slug) DO NOTHING;

-- 2. Insert Super Admin User
-- Hash: bcrypt(Admin@2025! + some-random-string-for-password-hashing)
-- This matches PASSWORD_PEPPER from deployed backend .env
INSERT INTO users (identifier, password_hash, role, full_name, email, status, active)
VALUES (
    'superadmin',
    '$2a$10$x7AN/r8MpVylJnd2uq4HT.lZbbNCqHuBuadpsr4xV.KlsleITmR5.',
    'superadmin',
    'Super Administrator',
    'admin@gohorsejobs.com',
    'active',
    true
) ON CONFLICT (identifier) DO UPDATE SET 
    password_hash = EXCLUDED.password_hash,
    status = 'active';

-- 3. Assign superadmin role (if user_roles table exists)
DO $$
BEGIN
    IF EXISTS (SELECT FROM pg_tables WHERE tablename = 'user_roles') THEN
        INSERT INTO user_roles (user_id, role)
        SELECT id, 'superadmin' FROM users WHERE identifier = 'superadmin'
        ON CONFLICT (user_id, role) DO NOTHING;
    END IF;
END $$;

