-- =====================================================================================
-- Schema Update: ml_orders 字段补齐
-- 位置：docs/sql/10_schema/order/
-- 对象类型：Schema (ALTER TABLE)
-- 版本：v1
-- 说明：为订单主表补齐核销记录 RPC 所依赖的业务字段（order_type, verified_at, verifier_id）
-- =====================================================================================

DO $$ 
BEGIN
    -- 1. 补齐 order_type (1:普通, 2:收银, 3:核销)
    IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'ml_orders' AND column_name = 'order_type') THEN
        ALTER TABLE public.ml_orders ADD COLUMN order_type INTEGER DEFAULT 1;
        COMMENT ON COLUMN public.ml_orders.order_type IS '订单类型: 1:普通, 2:收银, 3:核销';
    END IF;

    -- 2. 补齐 verified_at (核销时间)
    IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'ml_orders' AND column_name = 'verified_at') THEN
        ALTER TABLE public.ml_orders ADD COLUMN verified_at TIMESTAMP WITH TIME ZONE;
        COMMENT ON COLUMN public.ml_orders.verified_at IS '核销时间';
    END IF;

    -- 3. 补齐 verifier_id (核销员ID)
    IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'ml_orders' AND column_name = 'verifier_id') THEN
        ALTER TABLE public.ml_orders ADD COLUMN verifier_id UUID REFERENCES public.ak_users(id);
        COMMENT ON COLUMN public.ml_orders.verifier_id IS '核销员ID';
    END IF;

    -- 4. 补齐 pay_type (支付方式: 1:余额, 2:微信, 3:支付宝, 4:线下支付)
    IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'ml_orders' AND column_name = 'pay_type') THEN
        ALTER TABLE public.ml_orders ADD COLUMN pay_type INTEGER DEFAULT 1;
        COMMENT ON COLUMN public.ml_orders.pay_type IS '支付方式: 1:余额, 2:微信, 3:支付宝, 4:线下支付';
    END IF;

    -- 5. 补齐 channel_type (订单渠道: 1:公众号, 2:小程序, 3:H5, 4:PC, 5:APP)
    IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'ml_orders' AND column_name = 'channel_type') THEN
        ALTER TABLE public.ml_orders ADD COLUMN channel_type INTEGER DEFAULT 1;
        COMMENT ON COLUMN public.ml_orders.channel_type IS '订单渠道: 1:公众号, 2:小程序, 3:H5, 4:PC, 5:APP';
    END IF;

END $$;
