-- Phase 2: Token Plan / Coding Plan 基础目录清单

CREATE TABLE IF NOT EXISTS plan_catalog_inventory (
    id               BIGSERIAL PRIMARY KEY,
    provider_id      BIGINT REFERENCES model_provider(id) ON DELETE SET NULL,
    operator_id      BIGINT REFERENCES operator(id) ON DELETE SET NULL,
    catalog_code     TEXT NOT NULL UNIQUE,
    platform_name    TEXT NOT NULL,
    platform_name_cn TEXT,
    platform_type    TEXT NOT NULL,
    plan_family      TEXT NOT NULL,
    plan_status      TEXT NOT NULL DEFAULT 'confirmed',
    source_url       TEXT NOT NULL,
    source_title     TEXT,
    source_kind      TEXT NOT NULL DEFAULT 'official_doc',
    region           TEXT NOT NULL DEFAULT 'global',
    currency         TEXT,
    billing_cycle    TEXT,
    last_checked_at  TIMESTAMP NOT NULL,
    importer_key     TEXT,
    notes            TEXT,
    created_at       TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at       TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    created_by       TEXT DEFAULT 'system',
    updated_by       TEXT DEFAULT 'system',
    CONSTRAINT chk_plan_catalog_platform_type
        CHECK (platform_type IN ('official_vendor', 'cloud_operator', 'relay_platform')),
    CONSTRAINT chk_plan_catalog_family
        CHECK (plan_family IN ('token_plan', 'coding_plan', 'package_plan', 'pay_as_you_go', 'unknown')),
    CONSTRAINT chk_plan_catalog_status
        CHECK (plan_status IN ('confirmed', 'pending_verification', 'retired')),
    CONSTRAINT chk_plan_catalog_source_kind
        CHECK (source_kind IN ('official_doc', 'official_pricing', 'official_product_page', 'official_community', 'inferred')),
    CONSTRAINT chk_plan_catalog_currency
        CHECK (currency IS NULL OR currency IN ('CNY', 'USD', 'EUR'))
);

CREATE INDEX IF NOT EXISTS idx_plan_catalog_provider_id ON plan_catalog_inventory(provider_id);
CREATE INDEX IF NOT EXISTS idx_plan_catalog_operator_id ON plan_catalog_inventory(operator_id);
CREATE INDEX IF NOT EXISTS idx_plan_catalog_family ON plan_catalog_inventory(plan_family);
CREATE INDEX IF NOT EXISTS idx_plan_catalog_platform_type ON plan_catalog_inventory(platform_type);
CREATE INDEX IF NOT EXISTS idx_plan_catalog_status ON plan_catalog_inventory(plan_status);
CREATE INDEX IF NOT EXISTS idx_plan_catalog_last_checked_at ON plan_catalog_inventory(last_checked_at);

COMMENT ON TABLE plan_catalog_inventory IS 'Token Plan / Coding Plan / 套餐包 / 按量计费基础目录清单，用于后续 importer 排期与证据管理';

DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_proc WHERE proname = 'update_updated_at_column')
       AND NOT EXISTS (
           SELECT 1
           FROM pg_trigger
           WHERE tgname = 'plan_catalog_inventory_updated_at'
       ) THEN
        CREATE TRIGGER plan_catalog_inventory_updated_at
        BEFORE UPDATE ON plan_catalog_inventory
        FOR EACH ROW
        EXECUTE FUNCTION update_updated_at_column();
    END IF;
END
$$;
