-- performance_settings: singleton config row for the weekly ranking
-- pipeline, same pattern as invoice_settings (0013) — nested config
-- objects as jsonb, matching that table's own convention for small
-- fixed-shape settings blobs rather than exploding each into a column.
--
-- Ported from legacy state.weights/shiftMultipliers/shiftResolutionOffsets/
-- adminBonusRate/adminBonusCap (JavaScript.html:715-727, 743-751).
-- Confirmed in conversation: none of this existed anywhere in the live
-- schema before this migration.
--
-- Also adds commslayer_reports.admin_bonus_points — the per-agent-per-day
-- ADMIN-ENTERED points value (JavaScript.html:2649:
-- report.adminBonus[agentId] = pts), which legacy stores in the exact
-- same per-date report bucket as the Commslayer-synced metrics. This is
-- NOT Commslayer data and is not fetched by /api/commslayer-sync — it's
-- set by an admin via the (upcoming) Admin Bonus editor in /performance,
-- which converts entered hours to points at input time
-- (pts = min(round(hrs*rate*10)/10, cap), JavaScript.html:2647) using
-- admin_bonus_rate/admin_bonus_cap from performance_settings below.
--
-- RLS: view + write both gated on has_permission('performance', ...),
-- same as every other table in this feature domain. Singleton row —
-- only select/update policies exist (matching invoice_settings), no
-- insert/delete beyond the one seeded row.

create table if not exists public.performance_settings (
  id                        int primary key default 1,
  weights                   jsonb not null default '{"closedTickets":35,"oneTouch":25,"avgResponse":20,"resolution":20}'::jsonb,
  shift_multipliers         jsonb not null default '{"REGULAR":0,"EARLY":0,"LATE":20,"SAT":0,"HALF":0,"NSD":0,"OFF":0}'::jsonb,
  shift_resolution_offsets  jsonb not null default '{"REGULAR":480,"EARLY":480,"LATE":0,"SAT":0,"HALF":0,"NSD":0,"OFF":0}'::jsonb,
  admin_bonus_rate          numeric not null default 5,
  admin_bonus_cap           numeric not null default 35,
  updated_at                timestamptz not null default now(),
  constraint performance_settings_singleton check (id = 1)
);

insert into public.performance_settings (id)
values (1)
on conflict (id) do nothing;

alter table public.performance_settings enable row level security;

create policy "performance_settings_select"
on public.performance_settings
for select
to authenticated
using (public.has_permission('performance'));

create policy "performance_settings_update"
on public.performance_settings
for update
to authenticated
using (public.has_permission('performance', need_write => true))
with check (public.has_permission('performance', need_write => true));

-- ============================================================
-- commslayer_reports.admin_bonus_points
-- ============================================================

alter table public.commslayer_reports
  add column if not exists admin_bonus_points numeric not null default 0;
