BEGIN;

CREATE TABLE IF NOT EXISTS apps (
    id VARCHAR(32) PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    description TEXT,
    status VARCHAR(20) NOT NULL DEFAULT 'active',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS tenant_entitlements (
    tenant_id UUID PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE,
    enabled_apps TEXT[] NOT NULL DEFAULT '{}',
    version INTEGER NOT NULL DEFAULT 0,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS tenant_enabled_apps_history (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    version INTEGER NOT NULL,
    enabled_apps TEXT[] NOT NULL,
    actor_user_id UUID,
    reason TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

INSERT INTO tenants (id, name, config)
VALUES (
    '00000000-0000-0000-0000-000000000001',
    'Platform',
    jsonb_build_object('enabled_apps', jsonb_build_array(), 'enabled_apps_version', 0)
)
ON CONFLICT (id) DO NOTHING;

INSERT INTO apps (id, name, description) VALUES
('iam', 'IAM', 'Identity and Access Management'),
('cms', 'CMS', 'Content Management Platform'),
('tms', 'TMS', 'Task Management Platform')
ON CONFLICT (id) DO NOTHING;

INSERT INTO tenant_entitlements (tenant_id, enabled_apps, version)
SELECT t.id, '{}'::text[], 0
FROM tenants t
ON CONFLICT (tenant_id) DO NOTHING;

UPDATE tenant_entitlements
SET enabled_apps = ARRAY['tms']::text[]
WHERE tenant_id = '11111111-1111-1111-1111-111111111111'
  AND enabled_apps = '{}'::text[];

UPDATE tenants
SET config =
    jsonb_set(
        jsonb_set(COALESCE(config, '{}'::jsonb), '{enabled_apps}', to_jsonb(te.enabled_apps), true),
        '{enabled_apps_version}', to_jsonb(te.version), true
    )
FROM tenant_entitlements te
WHERE tenants.id = te.tenant_id;

INSERT INTO permissions (code, description, resource, action) VALUES
('iam:tenant:enabled_apps:read', 'Read tenant enabled apps', 'tenant_enabled_apps', 'read'),
('iam:tenant:enabled_apps:write', 'Manage tenant enabled apps', 'tenant_enabled_apps', 'write')
ON CONFLICT (code) DO NOTHING;

INSERT INTO roles (tenant_id, name, description, is_system)
VALUES ('00000000-0000-0000-0000-000000000001', 'SuperAdmin', 'Platform super administrator', TRUE)
ON CONFLICT (tenant_id, name) DO NOTHING;

DELETE FROM role_permissions rp
USING roles r, permissions p
WHERE rp.role_id = r.id
  AND rp.permission_id = p.id
  AND r.name = 'Admin'
  AND r.tenant_id <> '00000000-0000-0000-0000-000000000001'
  AND p.code LIKE 'iam:%';

INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r, permissions p
WHERE r.name = 'SuperAdmin'
  AND r.tenant_id = '00000000-0000-0000-0000-000000000001'
  AND p.code IN ('iam:tenant:enabled_apps:read', 'iam:tenant:enabled_apps:write')
ON CONFLICT DO NOTHING;

COMMIT;

