-- PATCH 2: Permission catalog + role mapping (minimal)
-- Run once (safe with INSERT IGNORE)

INSERT IGNORE INTO permissions (code,label) VALUES
('dashboard.view','Lihat dashboard'),
('pos.view','Akses POS'),
('pos.add','Tambah order POS'),
('pos.edit','Edit order POS'),
('pos.print','Print order POS'),
('pos.export','Export POS'),
('customer.view','Lihat customer'),
('customer.add','Tambah customer'),
('customer.edit','Edit customer'),
('customer.export','Export customer'),
('produk.view','Lihat produk'),
('produk.add','Tambah produk'),
('produk.edit','Edit produk'),
('produk.export','Export produk'),
('settings.branding.manage','Kelola branding'),
('settings.locations.manage','Kelola lokasi'),
('settings.users.manage','Kelola users'),
('settings.roles.manage','Kelola roles & permissions'),
('reports.view','Lihat laporan'),
('reports.export','Export laporan');

-- Ensure default roles exist
INSERT INTO roles (tenant_id,name,is_system) VALUES
(1,'owner',1),
(1,'admin',1),
(1,'kepala_toko',1),
(1,'kasir',1),
(1,'karyawan',1)
ON DUPLICATE KEY UPDATE name=VALUES(name);

-- Admin: all permissions
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r CROSS JOIN permissions p
WHERE r.tenant_id=1 AND r.name='admin';

-- Kepala toko: dashboard + customer + produk + reports
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r JOIN permissions p
WHERE r.tenant_id=1 AND r.name='kepala_toko'
AND p.code IN ('dashboard.view','customer.view','customer.add','customer.edit','customer.export',
               'produk.view','produk.add','produk.edit','produk.export',
               'reports.view','reports.export');

-- Kasir: POS only
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r JOIN permissions p
WHERE r.tenant_id=1 AND r.name='kasir'
AND p.code IN ('dashboard.view','pos.view','pos.add','pos.edit','pos.print');

-- Karyawan: view customer+produk
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r JOIN permissions p
WHERE r.tenant_id=1 AND r.name='karyawan'
AND p.code IN ('dashboard.view','customer.view','produk.view');

-- Owner role mapping optional (owner bypass anyway): give all for completeness
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r CROSS JOIN permissions p
WHERE r.tenant_id=1 AND r.name='owner';
