CREATE TABLE IF NOT EXISTS bazzar_pos.permissions (
    id BIGSERIAL PRIMARY KEY,
    key VARCHAR(120) NOT NULL UNIQUE,
    label VARCHAR(150) NOT NULL,
    module VARCHAR(80) NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS bazzar_pos.role_permissions (
    role_id BIGINT NOT NULL REFERENCES bazzar_pos.roles(id) ON DELETE CASCADE,
    permission_id BIGINT NOT NULL REFERENCES bazzar_pos.permissions(id) ON DELETE CASCADE,
    PRIMARY KEY (role_id, permission_id)
);

CREATE TABLE IF NOT EXISTS bazzar_pos.user_permissions (
    user_id BIGINT NOT NULL REFERENCES bazzar_pos.users(id) ON DELETE CASCADE,
    permission_id BIGINT NOT NULL REFERENCES bazzar_pos.permissions(id) ON DELETE CASCADE,
    is_allowed BOOLEAN NOT NULL,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (user_id, permission_id)
);

INSERT INTO bazzar_pos.permissions (key, label, module)
VALUES
    ('dashboard.view', 'Dashboard', 'dashboard'),
    ('pos.sell', 'POS Sell', 'pos'),
    ('pos.return', 'POS Return', 'pos'),
    ('report.sales.view', 'Sales Report', 'report'),
    ('stock.view', 'Stock View', 'stock'),
    ('stock.adjust', 'Stock Adjust', 'stock'),
    ('master_data.manage', 'Master Data Manage', 'master_data'),
    ('pricing.approval.manage', 'Pricing Approval', 'pricing'),
    ('settings.general.manage', 'Settings General', 'settings'),
    ('settings.users.manage', 'Settings Users', 'settings'),
    ('settings.danger_zone.execute', 'Danger Zone Execute', 'settings')
ON CONFLICT (key) DO NOTHING;

INSERT INTO bazzar_pos.role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM bazzar_pos.roles r
JOIN bazzar_pos.permissions p ON TRUE
WHERE r.code = 'superadmin'
ON CONFLICT DO NOTHING;

INSERT INTO bazzar_pos.role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM bazzar_pos.roles r
JOIN bazzar_pos.permissions p ON p.key IN (
    'dashboard.view',
    'pos.sell',
    'pos.return',
    'report.sales.view',
    'stock.view',
    'stock.adjust',
    'master_data.manage',
    'settings.general.manage',
    'settings.users.manage',
    'settings.danger_zone.execute'
)
WHERE r.code = 'admin'
ON CONFLICT DO NOTHING;

INSERT INTO bazzar_pos.role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM bazzar_pos.roles r
JOIN bazzar_pos.permissions p ON p.key IN (
    'dashboard.view',
    'pos.sell',
    'pos.return',
    'report.sales.view',
    'stock.view'
)
WHERE r.code = 'cashier'
ON CONFLICT DO NOTHING;

CREATE INDEX IF NOT EXISTS idx_user_permissions_user_id
    ON bazzar_pos.user_permissions(user_id);
