-- =====================================================================================
-- Schema: 发票管理表
-- 位置：docs/sql/10_schema/finance/ml_invoices_v1.sql
-- 对象类型：Schema (DDL)
-- 版本：v1
-- 说明：记录用户提交的开票申请及其处理状态
-- =====================================================================================

CREATE TABLE IF NOT EXISTS public.ml_invoices (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  uid UUID NOT NULL REFERENCES public.ak_users(id),
  order_no TEXT NOT NULL,           -- 关联订单号
  
  order_amount DECIMAL(12,2) NOT NULL, -- 订单金额
  
  invoice_type SMALLINT NOT NULL DEFAULT 1, -- 1: 电子普通发票, 2: 增值税专用发票
  header_type SMALLINT NOT NULL DEFAULT 1,  -- 1: 个人, 2: 企业
  
  header_name TEXT NOT NULL,        -- 发票抬头
  tax_id TEXT NULL,                 -- 企业税号
  
  email TEXT NULL,                  -- 接收邮箱
  remark TEXT NULL,                 -- 备注
  
  status SMALLINT NOT NULL DEFAULT 0, -- 0: 待开票, 1: 已开票, -1: 已拒绝
  refusal_reason TEXT NULL,           -- 驳回原因
  invoice_url TEXT NULL,              -- 电子发票文件路径/URL
  
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- 索引
CREATE INDEX IF NOT EXISTS ml_invoices_uid_idx ON public.ml_invoices (uid);
CREATE INDEX IF NOT EXISTS ml_invoices_order_no_idx ON public.ml_invoices (order_no);
CREATE INDEX IF NOT EXISTS ml_invoices_status_idx ON public.ml_invoices (status);
