BEGIN;

INSERT INTO departments (id, name, code, path, created_at, updated_at)
VALUES (
    '11111111-2222-3333-4444-555555555555'::uuid,
    'System',
    'SYSTEM',
    'system'::ltree,
    CURRENT_TIMESTAMP,
    CURRENT_TIMESTAMP
) ON CONFLICT (id) DO NOTHING;

INSERT INTO users (
    id, 
    username,
    email, 
    name, 
    password_hash,
    status,
    is_active,
    created_at, 
    updated_at
)
VALUES (
    '11111111-2222-3333-4444-555555555555'::uuid,
    'system',
    'system@eslogad.internal',
    'System User',
    '$2a$10$SYSTEM.USER.SHOULD.NEVER.LOGIN.WITH.PASSWORD.HASH',
    'active',
    true,
    CURRENT_TIMESTAMP,
    CURRENT_TIMESTAMP
) ON CONFLICT (id) DO NOTHING;

-- Create user profile for system user
INSERT INTO user_profiles (
    user_id,
    full_name,
    display_name,
    job_title,
    preferences,
    notification_prefs,
    created_at,
    updated_at
)
VALUES (
    '11111111-2222-3333-4444-555555555555'::uuid,
    'System User',
    'System',
    'Automated Process',
    '{}'::jsonb,
    '{}'::jsonb,
    CURRENT_TIMESTAMP,
    CURRENT_TIMESTAMP
) ON CONFLICT (user_id) DO NOTHING;

-- Link system user to system department
INSERT INTO user_department (
    id,
    user_id,
    department_id,
    is_primary,
    assigned_at,
    removed_at
)
VALUES (
    gen_random_uuid(),
    '11111111-2222-3333-4444-555555555555'::uuid,
    '11111111-2222-3333-4444-555555555555'::uuid,
    true,
    CURRENT_TIMESTAMP,
    NULL
) ON CONFLICT (user_id, department_id) WHERE removed_at IS NULL DO NOTHING;

-- Optionally, create a system role if your application uses roles
-- Uncomment and modify if needed:
-- INSERT INTO roles (id, code, name, description, created_at, updated_at)
-- VALUES (
--     gen_random_uuid(),
--     'SYSTEM',
--     'System Role',
--     'Role for system automated processes',
--     CURRENT_TIMESTAMP,
--     CURRENT_TIMESTAMP
-- ) ON CONFLICT (code) DO NOTHING;

COMMIT;