-- 003_master_patch3.sql (Sprint 3 Patch 3)
-- Master Data: Units (Satuan) + Categories (Kategori)
-- Requires: 001_core.sql + 002_auth.sql already applied


-- Units
CREATE TABLE IF NOT EXISTS units (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  tenant_id BIGINT UNSIGNED NOT NULL,
  code VARCHAR(32) NOT NULL,
  name VARCHAR(120) NOT NULL,
  allow_decimal TINYINT(1) NOT NULL DEFAULT 0,
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_units_tenant_code (tenant_id, code),
  KEY idx_units_tenant_active (tenant_id, is_active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Categories
CREATE TABLE IF NOT EXISTS categories (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  tenant_id BIGINT UNSIGNED NOT NULL,
  code VARCHAR(32) NOT NULL,
  name VARCHAR(120) NOT NULL,
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_categories_tenant_code (tenant_id, code),
  KEY idx_categories_tenant_active (tenant_id, is_active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Permission catalog (Master Data)
INSERT IGNORE INTO permissions (code, module, action, name) VALUES
('master.units.view','master.units','view','Lihat Satuan'),
('master.units.add','master.units','add','Tambah Satuan'),
('master.units.edit','master.units','edit','Edit Satuan'),
('master.units.print','master.units','print','Print Satuan'),
('master.units.export','master.units','export','Export Satuan'),

('master.categories.view','master.categories','view','Lihat Kategori'),
('master.categories.add','master.categories','add','Tambah Kategori'),
('master.categories.edit','master.categories','edit','Edit Kategori'),
('master.categories.print','master.categories','print','Print Kategori'),
('master.categories.export','master.categories','export','Export Kategori');

-- Auto grant to Owner + Admin across tenants
INSERT IGNORE INTO role_permissions(role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p
WHERE r.code IN ('owner','admin')
  AND p.code IN (
    'master.units.view','master.units.add','master.units.edit','master.units.print','master.units.export',
    'master.categories.view','master.categories.add','master.categories.edit','master.categories.print','master.categories.export'
  );

