-- Flexible permissions: product cost visibility, financial reports, expenses, POS returns, settings migrations
-- Idempotent INSERT IGNORE

INSERT IGNORE INTO permissions (code, description) VALUES
('product.cost.view', 'View product cost price and purchase cost fields'),
('report.cost.view', 'View financial reports that expose cost, COGS, and margins'),
('expense.view', 'View expenses list'),
('expense.edit', 'Create, edit, and delete expenses and recurring templates'),
('pos.view', 'View returns'),
('pos.create', 'Create returns'),
('settings.update', 'Run database migrations and update rental terms');

-- Grant new codes to Admin role (id = 1)
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT 1, id FROM permissions WHERE code IN (
    'product.cost.view',
    'report.cost.view',
    'expense.view',
    'expense.edit',
    'pos.view',
    'pos.create',
    'settings.update'
);

-- Roles that can edit products usually need expenses, returns, and financial/cost visibility
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT DISTINCT rp.role_id, p.id
FROM role_permissions rp
JOIN permissions px ON px.id = rp.permission_id AND px.code = 'product.edit'
CROSS JOIN permissions p
WHERE p.code IN (
    'product.cost.view',
    'report.cost.view',
    'expense.view',
    'expense.edit',
    'pos.view',
    'pos.create'
);
