-- 023 — Gang payroll system (Phase 15, 19-04-2026)
-- Paye quotidienne des gangsters à 00:00 Paris. Si trésorerie gang <= 0 pour
-- la devise choisie → gangster marqué unpaid_since, refuse les ordres tant
-- qu'il n'est pas payé. Mise en cache daily_salary pour perf.
-- Idempotent (ADD COLUMN IF NOT EXISTS).

ALTER TABLE gang_members ADD COLUMN IF NOT EXISTS unpaid_since TIMESTAMP;
ALTER TABLE gang_members ADD COLUMN IF NOT EXISTS daily_salary INT NOT NULL DEFAULT 50;
ALTER TABLE gang_members ADD COLUMN IF NOT EXISTS total_paid BIGINT NOT NULL DEFAULT 0;

CREATE INDEX IF NOT EXISTS idx_gang_members_unpaid ON gang_members(unpaid_since)
  WHERE unpaid_since IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_gang_members_gang_player ON gang_members(gang_id, player_id);

-- Historique des paies (audit trail, debug désertions)
CREATE TABLE IF NOT EXISTS gang_payroll_events (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  gang_id UUID NOT NULL,
  player_id UUID NOT NULL,
  amount INT NOT NULL,
  currency VARCHAR(20) NOT NULL DEFAULT 'infinite_shadow',
  paid BOOLEAN NOT NULL,
  reason VARCHAR(40), -- 'daily', 'unpaid_insufficient', 'deserted', 'kicked'
  occurred_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_gang_payroll_events_player ON gang_payroll_events(player_id, occurred_at DESC);
CREATE INDEX IF NOT EXISTS idx_gang_payroll_events_gang ON gang_payroll_events(gang_id, occurred_at DESC);

-- NpcRecruitPool : champ daily_salary sur les slots (calculé lors de refresh) —
-- inutile en colonne car `slots` est JSONB. Le champ est ajouté dans le type TS
-- NpcRecruitSlot. Pas de migration SQL requise.
