-- ============================================
-- 创建审计日志表
-- 用于记录敏感操作，便于安全审计
-- ============================================

-- 创建审计日志表
CREATE TABLE IF NOT EXISTS public.audit_logs (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
  company_id UUID REFERENCES public.companies(id) ON DELETE SET NULL,
  action TEXT NOT NULL, -- 操作类型：login, logout, create, update, delete, export, etc.
  resource_type TEXT NOT NULL, -- 资源类型：plan, factory, warehouse, payment, profile, etc.
  resource_id UUID, -- 被操作资源的ID
  details JSONB, -- 操作详情（JSON格式）
  ip_address TEXT, -- IP地址
  user_agent TEXT, -- 用户代理
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- 创建索引
CREATE INDEX idx_audit_logs_user_id ON public.audit_logs(user_id);
CREATE INDEX idx_audit_logs_company_id ON public.audit_logs(company_id);
CREATE INDEX idx_audit_logs_action ON public.audit_logs(action);
CREATE INDEX idx_audit_logs_created_at ON public.audit_logs(created_at DESC);

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

-- 审计日志策略：用户只能查看自己公司的日志
CREATE POLICY users_select_company_audit_logs ON public.audit_logs
FOR SELECT USING (
  company_id = public.get_user_master_company_id()
);

-- 允许插入日志（应用层写入）
CREATE POLICY users_insert_audit_logs ON public.audit_logs
FOR INSERT WITH CHECK (true);

-- 禁止修改和删除审计日志（保证不可篡改）
-- 不提供 UPDATE 和 DELETE 策略

-- 注释
COMMENT ON TABLE public.audit_logs IS '审计日志表，记录所有敏感操作';
COMMENT ON COLUMN public.audit_logs.action IS '操作类型：login, logout, create, update, delete, export';
COMMENT ON COLUMN public.audit_logs.resource_type IS '被操作的资源类型';
COMMENT ON COLUMN public.audit_logs.details IS '操作详情，JSON格式存储变更前后数据';
