-- Schema: 医疗商城独立分类与商品分类关联
-- 执行阶段: 10_schema

CREATE TABLE IF NOT EXISTS public.medical_mall_categories (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    parent_id TEXT NULL REFERENCES public.medical_mall_categories(id),
    level INTEGER NOT NULL CHECK (level IN (1, 2)),
    sort_order INTEGER NOT NULL DEFAULT 0,
    icon TEXT,
    image_url TEXT,
    description TEXT,
    scene TEXT NOT NULL DEFAULT 'medical_mall',
    category_type TEXT NOT NULL DEFAULT 'normal',
    compliance_type TEXT NOT NULL DEFAULT 'normal',
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    deleted_at TIMESTAMPTZ NULL,
    deleted_by UUID NULL REFERENCES public.ak_users(id),
    restored_at TIMESTAMPTZ NULL,
    restored_by UUID NULL REFERENCES public.ak_users(id),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

COMMENT ON TABLE public.medical_mall_categories IS '医疗商城独立分类表';
COMMENT ON COLUMN public.medical_mall_categories.scene IS '分类场景，如 medical_mall / home_mall';
COMMENT ON COLUMN public.medical_mall_categories.category_type IS '分类类型：device / otc / care / rehab / elderly / nutrition / protection / tcm / all';
COMMENT ON COLUMN public.medical_mall_categories.compliance_type IS '合规类型：normal / otc / device_class_i / device_class_ii / device_class_iii / rx_hidden';

CREATE INDEX IF NOT EXISTS idx_medical_mall_categories_parent
    ON public.medical_mall_categories(parent_id)
    WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_medical_mall_categories_level_sort
    ON public.medical_mall_categories(level, sort_order)
    WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_medical_mall_categories_scene_active
    ON public.medical_mall_categories(scene, is_active)
    WHERE deleted_at IS NULL;

CREATE TABLE IF NOT EXISTS public.medical_mall_product_categories (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    product_id UUID NOT NULL REFERENCES public.ml_products(id) ON DELETE CASCADE,
    category_id TEXT NOT NULL REFERENCES public.medical_mall_categories(id),
    is_primary BOOLEAN NOT NULL DEFAULT FALSE,
    sort_order INTEGER NOT NULL DEFAULT 0,
    deleted_at TIMESTAMPTZ NULL,
    deleted_by UUID NULL REFERENCES public.ak_users(id),
    restored_at TIMESTAMPTZ NULL,
    restored_by UUID NULL REFERENCES public.ak_users(id),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (product_id, category_id)
);

COMMENT ON TABLE public.medical_mall_product_categories IS '医疗商城商品与分类关联表';

CREATE INDEX IF NOT EXISTS idx_medical_mall_product_categories_category
    ON public.medical_mall_product_categories(category_id, sort_order)
    WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_medical_mall_product_categories_product
    ON public.medical_mall_product_categories(product_id)
    WHERE deleted_at IS NULL;