-- ============================================
-- 生产采购价变更记录表
-- ============================================

CREATE TABLE public.production_price_history (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  plan_id UUID NOT NULL REFERENCES public.production_plans(id) ON DELETE CASCADE,
  -- 变更信息
  old_price DECIMAL NOT NULL DEFAULT 0,
  new_price DECIMAL NOT NULL DEFAULT 0,
  change_amount DECIMAL NOT NULL DEFAULT 0,
  -- 操作人
  operator_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
  operator_name TEXT,
  -- 变更原因/备注
  change_reason TEXT,
  -- 时间
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- 添加索引
CREATE INDEX idx_price_history_plan ON public.production_price_history(plan_id);
CREATE INDEX idx_price_history_created ON public.production_price_history(created_at);

-- 启用 RLS
ALTER TABLE public.production_price_history ENABLE ROW LEVEL SECURITY;

-- RLS 策略
-- 采购商可以查看自己计划的价格变更记录
CREATE POLICY purchaser_select_price_history ON public.production_price_history
  FOR SELECT USING (
    EXISTS (
      SELECT 1 FROM public.production_plans p
      WHERE p.id = production_price_history.plan_id
      AND p.purchaser_id = get_user_master_company_id()
    )
  );

-- 纺织厂可以查看关联计划的价格变更记录
CREATE POLICY textile_select_price_history ON public.production_price_history
  FOR SELECT USING (
    EXISTS (
      SELECT 1 FROM public.production_plans p
      JOIN public.plan_factories pf ON pf.plan_id = p.id
      WHERE p.id = production_price_history.plan_id
      AND pf.factory_id = get_user_master_company_id()
    )
  );

-- 采购商可以创建价格变更记录
CREATE POLICY purchaser_insert_price_history ON public.production_price_history
  FOR INSERT WITH CHECK (
    EXISTS (
      SELECT 1 FROM public.production_plans p
      WHERE p.id = production_price_history.plan_id
      AND p.purchaser_id = get_user_master_company_id()
    )
  );
