-- Ensure baseline ACS test accounts exist in the Node/PostgreSQL deployment.
-- Passwords:
--   admin/security/host = ChangeMe123!
--   a/s/h               = 1

WITH upserted AS (
    INSERT INTO users (
        created_at,
        updated_at,
        username,
        password_hash,
        full_name,
        email,
        department,
        must_change_password,
        enabled,
        locked
    )
    VALUES
        (now(), now(), 'admin', '$2a$12$7FBM5I4IOmKQHmBbAm2AAu3HQ3FvOkazzuBk1Hnd.gr68UekEusEa', 'Admin', 'admin@itcenter.local', 'IT Ops', TRUE, TRUE, FALSE),
        (now(), now(), 'security', '$2a$12$7FBM5I4IOmKQHmBbAm2AAu3HQ3FvOkazzuBk1Hnd.gr68UekEusEa', 'Security', 'security@itcenter.local', 'Security', TRUE, TRUE, FALSE),
        (now(), now(), 'host', '$2a$12$7FBM5I4IOmKQHmBbAm2AAu3HQ3FvOkazzuBk1Hnd.gr68UekEusEa', 'Host', 'host@itcenter.local', 'Dev Team', TRUE, TRUE, FALSE),
        (now(), now(), 'a', '$2a$12$aQ84.8Z4w/9GLG4gJkBu7OAHU3v9/BR5ESLimxpnETZ.pxnzylgkW', 'Admin', 'a@itcenter.local', 'IT Ops', FALSE, TRUE, FALSE),
        (now(), now(), 's', '$2a$12$aQ84.8Z4w/9GLG4gJkBu7OAHU3v9/BR5ESLimxpnETZ.pxnzylgkW', 'Security', 's@itcenter.local', 'Security', FALSE, TRUE, FALSE),
        (now(), now(), 'h', '$2a$12$aQ84.8Z4w/9GLG4gJkBu7OAHU3v9/BR5ESLimxpnETZ.pxnzylgkW', 'Host', 'h@itcenter.local', 'Dev Team', FALSE, TRUE, FALSE)
    ON CONFLICT (username) DO UPDATE
        SET updated_at = now(),
            password_hash = EXCLUDED.password_hash,
            full_name = EXCLUDED.full_name,
            email = EXCLUDED.email,
            department = EXCLUDED.department,
            must_change_password = EXCLUDED.must_change_password,
            enabled = TRUE,
            locked = FALSE
    RETURNING id, username
)
DELETE FROM user_roles
WHERE user_id IN (SELECT id FROM upserted);

INSERT INTO user_roles (user_id, role)
SELECT id, role
FROM (
    SELECT id, 'ADMIN' AS role FROM users WHERE username IN ('admin', 'a')
    UNION ALL
    SELECT id, 'SECURITY' AS role FROM users WHERE username IN ('security', 's')
    UNION ALL
    SELECT id, 'HOST' AS role FROM users WHERE username IN ('host', 'h')
) seeded_roles;
