-- ============================================================
-- ADD ON - HITUNGAN OFFSET
-- ============================================================

-- VIEW
INSERT INTO permissions (code, name, module, created_at)
SELECT 'addon.offset.view', 'View Hitungan Offset', 'Add On', NOW()
WHERE NOT EXISTS (
    SELECT 1 FROM permissions WHERE code = 'addon.offset.view'
);

-- ADD / HITUNG
INSERT INTO permissions (code, name, module, created_at)
SELECT 'addon.offset.add', 'Hitung & Simpan Offset', 'Add On', NOW()
WHERE NOT EXISTS (
    SELECT 1 FROM permissions WHERE code = 'addon.offset.add'
);

-- DELETE
INSERT INTO permissions (code, name, module, created_at)
SELECT 'addon.offset.delete', 'Hapus Histori Offset', 'Add On', NOW()
WHERE NOT EXISTS (
    SELECT 1 FROM permissions WHERE code = 'addon.offset.delete'
);

-- Assign ke role owner
INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.code IN (
    'addon.offset.view',
    'addon.offset.add',
    'addon.offset.delete'
)
WHERE r.code = 'owner'
AND NOT EXISTS (
    SELECT 1 FROM role_permissions rp
    WHERE rp.role_id = r.id
      AND rp.permission_id = p.id
);

-- Assign ke role admin
INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.code IN (
    'addon.offset.view',
    'addon.offset.add',
    'addon.offset.delete'
)
WHERE r.code = 'admin'
AND NOT EXISTS (
    SELECT 1 FROM role_permissions rp
    WHERE rp.role_id = r.id
      AND rp.permission_id = p.id
);
