-- Compatibility bootstrap for empty production databases.
-- Run after scripts/init-db.sql and before/after scripts/seed.sql.

BEGIN;

CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE IF NOT EXISTS user_role_assignments (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    role_id UUID NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
    status VARCHAR(50) NOT NULL DEFAULT 'PENDING',
    approved_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(user_id, role_id)
);

CREATE INDEX IF NOT EXISTS idx_user_role_assignments_user_id
    ON user_role_assignments(user_id);

CREATE TABLE IF NOT EXISTS role_sidebar_configs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    role_id UUID NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
    audience VARCHAR(50) NOT NULL,
    config_json JSONB NOT NULL,
    version INTEGER NOT NULL DEFAULT 1,
    is_active BOOLEAN NOT NULL DEFAULT true,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_active_role_sidebar_per_role_audience
    ON role_sidebar_configs(role_id, audience) WHERE is_active = true;

CREATE TABLE IF NOT EXISTS role_runtime_configs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    role_id UUID NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
    config_json JSONB NOT NULL,
    version INTEGER NOT NULL DEFAULT 1,
    is_active BOOLEAN NOT NULL DEFAULT true,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_active_role_runtime_per_role
    ON role_runtime_configs(role_id) WHERE is_active = true;

INSERT INTO user_role_assignments (id, user_id, role_id, status, approved_at, created_at)
SELECT id, user_id, role_id, status, approved_at, created_at
FROM user_roles
ON CONFLICT (user_id, role_id) DO NOTHING;

INSERT INTO role_sidebar_configs (id, role_id, audience, config_json, version, is_active, updated_at)
SELECT id, role_id, audience, config_json, version, is_active, updated_at
FROM dashboard_configs
ON CONFLICT DO NOTHING;

INSERT INTO role_runtime_configs (id, role_id, config_json, version, is_active, updated_at)
SELECT id, role_id, config_json, version, is_active, updated_at
FROM runtime_configs
ON CONFLICT DO NOTHING;

INSERT INTO pricing_packages (name, role_key, package_type, tracecoins_amount, price_inr, description, is_active)
VALUES
    ('Starter Credits', 'COMPANY', 'TRACECOIN_BUNDLE', 100, 499, 'Starter company credit bundle for demo purchases.', true),
    ('Growth Credits', 'COMPANY', 'TRACECOIN_BUNDLE', 300, 1299, 'Growth company credit bundle for regular hiring.', true),
    ('Scale Credits', 'COMPANY', 'TRACECOIN_BUNDLE', 750, 2999, 'Scale company credit bundle for higher-volume recruitment.', true)
ON CONFLICT DO NOTHING;

COMMIT;
