-- ============================================================
-- Migration 008: Tenant Tag System + Notification Targeting Extensions
-- Phase 1: Precision push targeting foundation
-- ============================================================

-- 1. Tenant tag definitions (platform-level, managed by platform admins)
CREATE TABLE IF NOT EXISTS public.tenant_tags (
  id          UUID         PRIMARY KEY DEFAULT gen_random_uuid(),
  name        VARCHAR(50)  NOT NULL UNIQUE,   -- e.g. "高价值客户", "试用期", "即将流失"
  color       VARCHAR(20)  NOT NULL DEFAULT '#6366F1',
  description TEXT,
  created_by  VARCHAR(100),
  created_at  TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
  updated_at  TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

-- 2. Tenant ← → Tag assignments
CREATE TABLE IF NOT EXISTS public.tenant_tag_assignments (
  tenant_id  VARCHAR(100) NOT NULL,
  tag_id     UUID         NOT NULL REFERENCES public.tenant_tags(id) ON DELETE CASCADE,
  tagged_by  VARCHAR(100),
  tagged_at  TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
  PRIMARY KEY (tenant_id, tag_id)
);

CREATE INDEX IF NOT EXISTS idx_tta_tenant ON public.tenant_tag_assignments (tenant_id);
CREATE INDEX IF NOT EXISTS idx_tta_tag    ON public.tenant_tag_assignments (tag_id);

-- 3. Notification user-level targets (for SPECIFIC_USERS targeting)
CREATE TABLE IF NOT EXISTS public.notification_user_targets (
  id              UUID         PRIMARY KEY DEFAULT gen_random_uuid(),
  notification_id UUID         NOT NULL REFERENCES public.notifications(id) ON DELETE CASCADE,
  user_id         VARCHAR(100) NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_notif_user_targets_notif ON public.notification_user_targets (notification_id);
CREATE INDEX IF NOT EXISTS idx_notif_user_targets_user  ON public.notification_user_targets (user_id);

-- 4. Extend notifications table with new targeting columns
ALTER TABLE public.notifications
  ADD COLUMN IF NOT EXISTS target_tag_ids  UUID[]   DEFAULT NULL,
  -- Tag IDs for BY_TENANT_TAG targeting
  ADD COLUMN IF NOT EXISTS target_tag_logic VARCHAR(3) DEFAULT 'ANY',
  -- ANY: tenant has at least one tag; ALL: tenant has all tags
  ADD COLUMN IF NOT EXISTS target_plans    TEXT[]   DEFAULT NULL,
  -- ['free','pro','enterprise'] for BY_PLAN targeting
  ADD COLUMN IF NOT EXISTS target_statuses TEXT[]   DEFAULT NULL,
  -- ['active','suspended'] for BY_TENANT_STATUS targeting
  ADD COLUMN IF NOT EXISTS channel_key     VARCHAR(50) DEFAULT NULL;
  -- References notification_channels.key (Phase 2, nullable for now)

-- 5. Extended TargetType values (documentation via check constraint)
-- Existing: ALL, SPECIFIC_TENANTS
-- New: BY_TENANT_TAG, BY_PLAN, BY_TENANT_STATUS, SPECIFIC_USERS
-- Note: constraint not enforced to allow backward compat; validated in service layer
