-- 091: admin_todos — operator fulfillment task queue.
--
-- Service handlers (npi_provider, mcs150_update, state_trucking, boc3_filing,
-- hazmat_phmsa, mailbox_setup, carrier_closeout, ein_application, …) insert a
-- row here whenever a filing needs human action. This table was referenced by
-- the workers but never had a CREATE migration, so the inserts silently failed
-- in any environment without the table. This migration defines it.
--
-- The shared helper scripts/workers/telegram_notify.create_admin_todo() and the
-- inlined INSERTs all use the same column set:
--   (title, category, priority, order_number, service_slug, description, data, status)

CREATE TABLE IF NOT EXISTS admin_todos (
    id              SERIAL PRIMARY KEY,
    title           TEXT NOT NULL,
    category        TEXT NOT NULL DEFAULT 'filing',   -- filing, provisioning, review, …
    priority        TEXT NOT NULL DEFAULT 'normal',   -- low, normal, high, urgent
    order_number    TEXT,                             -- e.g. CO-ABCD1234 (nullable for ad-hoc tasks)
    service_slug    TEXT,                             -- which service generated this task
    description     TEXT NOT NULL DEFAULT '',
    data            JSONB NOT NULL DEFAULT '{}',      -- structured intake/context payload
    status          TEXT NOT NULL DEFAULT 'pending'
                    CHECK (status IN ('pending', 'in_progress', 'done', 'cancelled')),
    assigned_to     TEXT,                             -- operator email/handle (optional)
    notes           TEXT,                             -- operator working notes
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    completed_at    TIMESTAMPTZ
);

CREATE INDEX IF NOT EXISTS idx_admin_todos_status   ON admin_todos(status) WHERE status IN ('pending', 'in_progress');
CREATE INDEX IF NOT EXISTS idx_admin_todos_order    ON admin_todos(order_number);
CREATE INDEX IF NOT EXISTS idx_admin_todos_priority ON admin_todos(priority);
CREATE INDEX IF NOT EXISTS idx_admin_todos_created  ON admin_todos(created_at DESC);

COMMENT ON TABLE admin_todos IS
    'Operator fulfillment task queue; one row per filing that needs human action.';
