-- Stripe Financial Connections bank links (replaces Plaid).
-- One row per accounting bank account linked through Stripe Financial Connections.
create table if not exists accounting.stripe_bank_connections (
  id uuid primary key default gen_random_uuid(),
  company_id uuid not null references accounting.companies(id) on delete cascade,
  account_id uuid not null references accounting.accounts(id) on delete cascade,
  fc_account_id text not null,        -- Stripe Financial Connections account id (fca_...)
  fc_customer_id text,                -- Stripe customer used as the account holder (cus_...)
  institution_name text,
  last4 text,
  status text not null default 'active',
  last_sync_at timestamptz,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),
  unique (company_id, account_id)
);

create index if not exists idx_stripe_bank_conn_company on accounting.stripe_bank_connections(company_id);

alter table accounting.stripe_bank_connections enable row level security;

drop policy if exists "Accounting staff full access" on accounting.stripe_bank_connections;
create policy "Accounting staff full access" on accounting.stripe_bank_connections
  for all using (accounting.is_accounting_staff()) with check (accounting.is_accounting_staff());
drop policy if exists "Members CRUD stripe_bank_connections" on accounting.stripe_bank_connections;
create policy "Members CRUD stripe_bank_connections" on accounting.stripe_bank_connections
  for all using (accounting.is_company_member(company_id, auth.uid()))
  with check (accounting.is_company_member(company_id, auth.uid()));
drop policy if exists "Board view stripe_bank_connections" on accounting.stripe_bank_connections;
create policy "Board view stripe_bank_connections" on accounting.stripe_bank_connections
  for select using (accounting.is_company_board_member(company_id));

drop trigger if exists trg_stripe_bank_conn_updated on accounting.stripe_bank_connections;
create trigger trg_stripe_bank_conn_updated
  before update on accounting.stripe_bank_connections
  for each row execute function public.update_updated_at_column();

grant select, insert, update, delete on accounting.stripe_bank_connections to authenticated;
grant all on accounting.stripe_bank_connections to service_role;
