-- Migration: Create Super Admin and System Company
-- Description: Inserts the default System Company and Super Admin user.
-- Uses unified tables (companies, users, user_roles)
--
-- ⚠️  PEPPER CRITICAL: This hash was generated with PASSWORD_PEPPER=gohorse-pepper
--     The backend (Coolify env var PASSWORD_PEPPER) MUST be set to: gohorse-pepper
--     If the pepper does not match, ALL logins will fail with "invalid credentials".
--
-- Credentials: identifier=superadmin / password=Admin@2025!
-- Hash: bcrypt("Admin@2025!" + "gohorse-pepper", cost=10)
-- Generated with bcryptjs 2.4.x / golang.org/x/crypto/bcrypt — both compatible.

-- 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
INSERT INTO users (identifier, password_hash, role, full_name, email, status, active)
VALUES (
    'superadmin',
    '$2b$10$4759wJhnXnBpcwSnVZm9Eu.wTqGYVCHkxAU5a2NxhsFHU42nV3tzW',
    '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 $$;

