-- 计费系统数据库表结构

-- 使用量记录（usage_logs）
CREATE TABLE IF NOT EXISTS `usage_logs` (
  `id` VARCHAR(36) PRIMARY KEY,
  `merchant_id` VARCHAR(36) NOT NULL,
  `feature` VARCHAR(50) NOT NULL,
  `usage` INT NOT NULL,
  `source` VARCHAR(20) NOT NULL,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX `idx_merchant_feature` (`merchant_id`, `feature`),
  INDEX `idx_created_at` (`created_at`)
);

-- 账单记录（billing_records）
CREATE TABLE IF NOT EXISTS `billing_records` (
  `id` VARCHAR(36) PRIMARY KEY,
  `merchant_id` VARCHAR(36) NOT NULL,
  `total_amount` DECIMAL(10,2) NOT NULL,
  `status` VARCHAR(20) NOT NULL DEFAULT 'pending',
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `paid_at` TIMESTAMP NULL,
  INDEX `idx_merchant_status` (`merchant_id`, `status`),
  INDEX `idx_created_at` (`created_at`)
);

-- 账单明细（billing_items）
CREATE TABLE IF NOT EXISTS `billing_items` (
  `id` VARCHAR(36) PRIMARY KEY,
  `billing_id` VARCHAR(36) NOT NULL,
  `feature` VARCHAR(50) NOT NULL,
  `amount` DECIMAL(10,2) NOT NULL,
  `quantity` INT NOT NULL,
  `unit_price` DECIMAL(10,2) NOT NULL,
  INDEX `idx_billing_id` (`billing_id`),
  CONSTRAINT `fk_billing_items_billing_id` FOREIGN KEY (`billing_id`) REFERENCES `billing_records` (`id`) ON DELETE CASCADE
);

-- 产品 metrics（用于ROI计算）
CREATE TABLE IF NOT EXISTS `product_metrics` (
  `id` VARCHAR(36) PRIMARY KEY,
  `product_id` VARCHAR(36) NOT NULL,
  `clicks` INT DEFAULT 0,
  `orders` INT DEFAULT 0,
  `cost` DECIMAL(10,2) DEFAULT 0,
  `revenue` DECIMAL(10,2) DEFAULT 0,
  `roi` DECIMAL(10,2) DEFAULT 0,
  `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX `idx_product_id` (`product_id`)
);
