-- =====================================================================================
-- Migration: Auth 安全约束增强
-- 位置：docs/sql/10_schema/auth/ak_auth_security_constraints_v1.sql
-- 对象类型：ALTER TABLE / CONSTRAINT
-- 说明：增强 ak_users 与 auth.users 的关联安全性，防止孤儿数据
-- =====================================================================================

-- 1. 确保 ak_users.auth_id 存在外键约束指向 auth.users
-- 注意：Supabase 的 auth.users 表在 auth schema 下，需要确保权限正确
DO $$
BEGIN
    -- 检查是否已存在外键约束
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.table_constraints 
        WHERE constraint_name = 'fk_ak_users_auth_id' 
        AND table_name = 'ak_users'
    ) THEN
        -- 添加外键约束，当 auth.users 被删除时自动删除对应的 profile
        ALTER TABLE public.ak_users
        ADD CONSTRAINT fk_ak_users_auth_id
        FOREIGN KEY (auth_id) REFERENCES auth.users(id)
        ON DELETE CASCADE;
    END IF;
END $$;

-- 2. 为 auth_id 建立唯一索引，确保一个 auth 用户只有一个 profile
CREATE UNIQUE INDEX IF NOT EXISTS idx_ak_users_auth_id_unique 
ON public.ak_users(auth_id);

-- 3. 为 role 字段建立索引，加速权限查询
CREATE INDEX IF NOT EXISTS idx_ak_users_role 
ON public.ak_users(role);

-- 4. 添加检查约束，确保 role 字段只能是有效值
ALTER TABLE public.ak_users
DROP CONSTRAINT IF EXISTS chk_ak_users_role_valid;

ALTER TABLE public.ak_users
ADD CONSTRAINT chk_ak_users_role_valid
CHECK (role IN ('user', 'admin', 'staff', 'agent', 'kefu') OR role IS NULL);

-- 5. 为 ak_admin_roles 添加约束确保关联有效性
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.table_constraints 
        WHERE constraint_name = 'fk_ak_admin_roles_admin_id' 
        AND table_name = 'ak_admin_roles'
    ) THEN
        ALTER TABLE public.ak_admin_roles
        ADD CONSTRAINT fk_ak_admin_roles_admin_id
        FOREIGN KEY (admin_id) REFERENCES public.ak_users(id)
        ON DELETE CASCADE;
    END IF;
END $$;

-- 6. 为 ak_role_permissions 添加约束确保关联有效性
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.table_constraints 
        WHERE constraint_name = 'fk_ak_role_permissions_role_id' 
        AND table_name = 'ak_role_permissions'
    ) THEN
        ALTER TABLE public.ak_role_permissions
        ADD CONSTRAINT fk_ak_role_permissions_role_id
        FOREIGN KEY (role_id) REFERENCES public.ak_roles(id)
        ON DELETE CASCADE;
    END IF;
END $$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.table_constraints 
        WHERE constraint_name = 'fk_ak_role_permissions_permission_id' 
        AND table_name = 'ak_role_permissions'
    ) THEN
        ALTER TABLE public.ak_role_permissions
        ADD CONSTRAINT fk_ak_role_permissions_permission_id
        FOREIGN KEY (permission_id) REFERENCES public.ak_permissions(id)
        ON DELETE CASCADE;
    END IF;
END $$;