-- Rol bazlı izinler (mevcut kurulumlar için bir kez çalıştırın)

CREATE TABLE IF NOT EXISTS permissions (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  slug VARCHAR(64) NOT NULL UNIQUE,
  label VARCHAR(120) NOT NULL,
  category VARCHAR(60) NULL,
  sort_order INT UNSIGNED NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS role_permissions (
  role_id INT UNSIGNED NOT NULL,
  permission_id INT UNSIGNED NOT NULL,
  PRIMARY KEY (role_id, permission_id),
  CONSTRAINT fk_rp_role FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,
  CONSTRAINT fk_rp_perm FOREIGN KEY (permission_id) REFERENCES permissions(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT IGNORE INTO permissions (slug, label, category, sort_order) VALUES
('dashboard', 'Özet panel', 'genel', 1),
('policies', 'Poliçeler', 'islem', 10),
('collections', 'Tahsilatlar', 'islem', 20),
('customers', 'Sigortalılar', 'islem', 30),
('settings_products', 'Ayarlar — Ürünler', 'ayarlar', 40),
('settings_tali', 'Ayarlar — Tali', 'ayarlar', 50),
('activity_logs', 'Log kayıtları', 'ayarlar', 55),
('users_manage', 'Kullanıcı yönetimi', 'yonetim', 60),
('roles_configure', 'Rol yetkilerini düzenleme', 'yonetim', 70),
('records_delete', 'Kayıt silme (poliçe, sigortalı, ürün, tali vb.)', 'guvenlik', 80);

-- Varsayılan eşleme (tablo boşsa doldur)
INSERT IGNORE INTO role_permissions (role_id, permission_id) SELECT 1, id FROM permissions;
INSERT IGNORE INTO role_permissions (role_id, permission_id) SELECT 2, id FROM permissions WHERE slug NOT IN ('users_manage', 'roles_configure');
INSERT IGNORE INTO role_permissions (role_id, permission_id) SELECT 3, id FROM permissions WHERE slug IN ('dashboard', 'policies', 'collections', 'customers');
INSERT IGNORE INTO role_permissions (role_id, permission_id) SELECT 4, id FROM permissions WHERE slug IN ('dashboard', 'policies', 'customers');
