-- Per-agent billing profile: name, contact, bank details, personal hourly-
-- rate override, invoice-numbering prefix. Ported from
-- state.invoiceProfiles[agentId] / DEFAULT_INVOICE_PROFILE
-- (JavaScript.html:6832-6848).
--
-- Keyed by agent_id (free text, matching invoices.agent_id/schedule
-- .agent_id) rather than the Supabase auth user id directly — profiles
-- .agent_id is what links a signed-in user to one of these rows, mirroring
-- the legacy profileKeyForCurrentUser() -> state.invoiceProfiles[key]
-- relationship exactly.

create table if not exists public.invoice_profiles (
  agent_id         text primary key,
  full_name        text not null default '',
  email            text not null default '',
  address          text not null default '',
  pag_ibig_mp2     text not null default '',
  sss              text not null default '',
  bank             jsonb not null default '{"name":"","address":"","accountNumber":"","swift":""}'::jsonb,
  hourly_rate_usd  numeric,
  invoice_prefix   text not null default '',
  status           text not null default '',
  completed        boolean not null default false,
  updated_at       timestamptz not null default now()
);

alter table public.invoice_profiles enable row level security;

create policy "invoice_profiles_select_own"
on public.invoice_profiles
for select
to authenticated
using (agent_id = public.current_agent_id());

create policy "invoice_profiles_insert_own"
on public.invoice_profiles
for insert
to authenticated
with check (agent_id = public.current_agent_id());

create policy "invoice_profiles_update_own"
on public.invoice_profiles
for update
to authenticated
using (agent_id = public.current_agent_id())
with check (agent_id = public.current_agent_id());
