-- 002_saas_foundation.sql
-- Sprint 1 — SAAS FOUNDATION (Tenant, License, Location, Branding)
-- NOTE: Gunakan migrate tool: php tools/migrate.php up

CREATE TABLE IF NOT EXISTS `tenants` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `code` VARCHAR(30) NOT NULL,
  `name` VARCHAR(120) NOT NULL,
  `is_active` TINYINT(1) NOT NULL DEFAULT 1,
  `created_at` DATETIME NOT NULL,
  `updated_at` DATETIME NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq_code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `licenses` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `tenant_id` INT UNSIGNED NOT NULL,
  `feature_flags` TEXT NULL,
  `location_limit` INT UNSIGNED NOT NULL DEFAULT 1,
  `created_at` DATETIME NOT NULL,
  `updated_at` DATETIME NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq_tenant` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `locations` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `tenant_id` INT UNSIGNED NOT NULL,
  `code` VARCHAR(20) NOT NULL,
  `name` VARCHAR(120) NOT NULL,
  `address` VARCHAR(255) NOT NULL DEFAULT '',
  `is_active` TINYINT(1) NOT NULL DEFAULT 1,
  `created_at` DATETIME NOT NULL,
  `updated_at` DATETIME NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq_tenant_code` (`tenant_id`, `code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `location_branding` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `tenant_id` INT UNSIGNED NOT NULL,
  `location_id` INT UNSIGNED NOT NULL,
  `brand_name` VARCHAR(120) NOT NULL,
  `title` VARCHAR(190) NOT NULL,
  `logo_path` VARCHAR(255) NOT NULL DEFAULT '',
  `favicon_path` VARCHAR(255) NOT NULL DEFAULT '',
  `primary` CHAR(7) NOT NULL DEFAULT '#b00000',
  `sidebar_bg` CHAR(7) NOT NULL DEFAULT '#ffffff',
  `topbar_bg` CHAR(7) NOT NULL DEFAULT '#b00000',
  `footer_text` VARCHAR(190) NOT NULL DEFAULT '',
  `created_at` DATETIME NOT NULL,
  `updated_at` DATETIME NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq_tenant_location` (`tenant_id`, `location_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Seeder minimal (id 1) — aman jika di-run ulang
INSERT IGNORE INTO tenants (id, code, name, is_active, created_at, updated_at)
VALUES (1, 'DEFAULT', 'Default Tenant', 1, NOW(), NOW());

INSERT IGNORE INTO licenses (id, tenant_id, feature_flags, location_limit, created_at, updated_at)
VALUES (1, 1, '{"pos": true}', 3, NOW(), NOW());

INSERT IGNORE INTO locations (id, tenant_id, code, name, address, is_active, created_at, updated_at)
VALUES (1, 1, 'JKT', 'Lokasi Utama', 'Jakarta', 1, NOW(), NOW());

INSERT IGNORE INTO location_branding (id, tenant_id, location_id, brand_name, title, logo_path, favicon_path, `primary`, sidebar_bg, topbar_bg, footer_text, created_at, updated_at)
VALUES (1, 1, 1, 'RAJAWALI', 'RAJAWALI Core System', '', '', '#b00000', '#ffffff', '#b00000', 'RAJAWALI', NOW(), NOW());
