-- 0094_client_groups.sql
-- ----------------------------------------------------------------------------
-- CM-1: first-class client groups (mailing/segment lists) + the membership
-- join, plus the new `client_groups` permission resource (view/manage).
--
-- Idempotent: CREATE TABLE/INDEX IF NOT EXISTS + a guarded role backfill.
-- Safe to re-run.

-- ─── 1. client_groups (per-port named group) ────────────────────────────────
CREATE TABLE IF NOT EXISTS client_groups (
  id            text PRIMARY KEY DEFAULT gen_random_uuid()::text,
  port_id       text NOT NULL REFERENCES ports(id) ON DELETE CASCADE,
  name          text NOT NULL,
  description   text,
  color         text NOT NULL DEFAULT '#6B7280',
  mailchimp_tag text,
  archived_at   timestamptz,
  created_at    timestamptz NOT NULL DEFAULT now(),
  updated_at    timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_client_groups_port ON client_groups(port_id);
-- Per-port, case-insensitive name uniqueness among non-archived groups.
CREATE UNIQUE INDEX IF NOT EXISTS idx_client_groups_port_name
  ON client_groups(port_id, lower(name))
  WHERE archived_at IS NULL;

-- ─── 2. client_group_members (M2M join; carries port_id for tenant isolation) ─
CREATE TABLE IF NOT EXISTS client_group_members (
  group_id   text NOT NULL REFERENCES client_groups(id) ON DELETE CASCADE,
  client_id  text NOT NULL REFERENCES clients(id) ON DELETE CASCADE,
  port_id    text NOT NULL REFERENCES ports(id) ON DELETE CASCADE,
  created_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (group_id, client_id)
);

CREATE INDEX IF NOT EXISTS idx_cgm_client ON client_group_members(client_id);
CREATE INDEX IF NOT EXISTS idx_cgm_port ON client_group_members(port_id);

-- ─── 3. `client_groups` permission resource (view/manage) ────────────────────
-- New-key only + idempotent via the `? 'client_groups'` guard. Defaults to the
-- role's clients access (view ⟵ clients.view, manage ⟵ clients.create) so the
-- right roles light up without a manual per-role edit.
UPDATE roles
SET permissions = permissions || jsonb_build_object(
  'client_groups', jsonb_build_object(
    'view',   COALESCE((permissions->'clients'->>'view')::boolean,   false),
    'manage', COALESCE((permissions->'clients'->>'create')::boolean, false)
  )
)
WHERE permissions IS NOT NULL
  AND NOT (permissions ? 'client_groups');
