-- ============================================================
-- HeavyHaul Agent — broker order intake workflow (source doc 2026-09-07).
--
-- 1. Payment responsibility: when the broker chooses the Synchron Permits
--    purchase workflow he MUST choose who pays the permit-processing invoice
--    (broker | carrier). NULL = not applicable (carrier-upload flow).
--    NOTE (documented deviation): the source doc wants a 3-value enum with
--    'not_applicable'; we store NULL instead — revisit if the backend team
--    prefers the literal enum.
--
-- 2. Email templates: the admin dashboard stores editable templates with
--    full version history ("if an email template is edited incorrectly, it
--    can confuse carriers, brokers, and Synchron"). Actual SENDING is the
--    email backend (later). Where the Synchron intake/order email ADDRESS
--    lives is a backend/env decision — TODO, not a settings field here.
-- ============================================================

alter table public.trips
  add column payment_responsible_party text check (payment_responsible_party in ('broker', 'carrier'));

create table public.email_templates (
  id uuid primary key default gen_random_uuid(),
  key text not null unique,
  name text not null,
  subject text not null,
  body text not null,
  recipients_note text,
  cc_rules text,
  trigger_note text,
  internal_notes text,
  active boolean not null default true,
  updated_by text,
  updated_at timestamptz not null default now(),
  created_at timestamptz not null default now()
);

create table public.email_template_versions (
  id uuid primary key default gen_random_uuid(),
  template_id uuid not null references public.email_templates (id) on delete cascade,
  subject text not null,
  body text not null,
  edited_by text,
  reason text,
  created_at timestamptz not null default now()
);
create index email_template_versions_tpl_idx on public.email_template_versions (template_id, created_at);

alter table public.email_templates enable row level security;
alter table public.email_template_versions enable row level security;
