-- 015 — Spécialistes (avocats / comptables / indics) + rattachements polymorphes
-- Un specialist peut cumuler des rattachements, chacun payé séparément.
-- Max 3 actifs par (owner_type, owner_id, role).

CREATE TABLE IF NOT EXISTS specialists (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  role VARCHAR(20) NOT NULL CHECK (role IN ('lawyer','accountant','informant')),
  name VARCHAR(120) NOT NULL,
  skill_level INT NOT NULL CHECK (skill_level BETWEEN 1 AND 10),
  -- Salaire mensuel baseline 2000..15000 ; daily = ROUND(monthly / 30 / 10) * 10
  salary_monthly INT NOT NULL,
  salary_daily INT NOT NULL,
  is_npc BOOLEAN NOT NULL DEFAULT true,
  -- Lien optionnel vers un Player si le specialist est un joueur (freelance futur)
  player_id UUID,
  bio TEXT,
  avatar_url VARCHAR(500),
  created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_specialists_role_skill ON specialists(role, skill_level);

CREATE TABLE IF NOT EXISTS specialist_attachments (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  specialist_id UUID NOT NULL REFERENCES specialists(id) ON DELETE CASCADE,
  owner_type VARCHAR(10) NOT NULL CHECK (owner_type IN ('player','gang','cartel')),
  owner_id UUID NOT NULL,
  -- Si un specialist cumule N rattachements, chaque attachement a un rabais
  -- appliqué à son coût : 0 attach. = 0% ; 1 attach. additionnel = -20% ; etc.
  discount_pct DECIMAL(5,2) NOT NULL DEFAULT 0,
  -- Modifier actif (peut être désactivé si pas payé)
  is_active BOOLEAN NOT NULL DEFAULT true,
  inactive_reason VARCHAR(30), -- 'unpaid', 'fired', 'dissolved'
  hired_at TIMESTAMP NOT NULL DEFAULT NOW(),
  fired_at TIMESTAMP,
  last_paid_at TIMESTAMP,
  next_payment_due TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_spec_attach_owner ON specialist_attachments(owner_type, owner_id, is_active);
CREATE INDEX IF NOT EXISTS idx_spec_attach_specialist ON specialist_attachments(specialist_id);
CREATE INDEX IF NOT EXISTS idx_spec_attach_next_payment ON specialist_attachments(next_payment_due)
  WHERE is_active = true;
