alter table public.orders
  add column if not exists refunded_amount_cents integer not null default 0;

alter table public.payments
  add column if not exists refunded_amount_cents integer not null default 0;

alter table public.orders drop constraint if exists orders_status_check;
alter table public.orders
  add constraint orders_status_check
  check (status in ('pending', 'paid', 'failed', 'closed', 'partially_refunded', 'refunded'));

alter table public.payments drop constraint if exists payments_status_check;
alter table public.payments
  add constraint payments_status_check
  check (status in ('pending', 'paid', 'failed', 'cancelled', 'partially_refunded', 'refunded'));

alter table public.entitlements
  add column if not exists revoked_at timestamptz,
  add column if not exists revoked_by uuid references public.platform_users(id) on delete set null,
  add column if not exists revoked_reason text;

do $$
begin
  if not exists (select 1 from pg_constraint where conname = 'orders_refunded_amount_cents_check') then
    alter table public.orders
      add constraint orders_refunded_amount_cents_check check (refunded_amount_cents >= 0);
  end if;

  if not exists (select 1 from pg_constraint where conname = 'payments_refunded_amount_cents_check') then
    alter table public.payments
      add constraint payments_refunded_amount_cents_check check (refunded_amount_cents >= 0);
  end if;
end $$;

create table if not exists public.commerce_refund_requests (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null references public.tenants(id) on delete cascade,
  order_id uuid not null references public.orders(id) on delete cascade,
  payment_id uuid references public.payments(id) on delete set null,
  refund_no text not null,
  provider text,
  provider_refund_no text,
  status text not null default 'requested'
    check (status in ('requested', 'approved', 'processing', 'succeeded', 'failed', 'rejected', 'cancelled')),
  amount_cents integer not null check (amount_cents > 0),
  reason text,
  entitlement_action text not null default 'revoke_on_success'
    check (entitlement_action in ('none', 'revoke_on_success')),
  requested_by uuid references public.platform_users(id) on delete set null,
  reviewed_by uuid references public.platform_users(id) on delete set null,
  processed_by uuid references public.platform_users(id) on delete set null,
  requested_at timestamptz not null default now(),
  reviewed_at timestamptz,
  processed_at timestamptz,
  succeeded_at timestamptz,
  failed_at timestamptz,
  cancelled_at timestamptz,
  failure_reason text,
  metadata jsonb not null default '{}'::jsonb,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),
  unique (tenant_id, refund_no)
);

create table if not exists public.commerce_refund_events (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null references public.tenants(id) on delete cascade,
  refund_request_id uuid not null references public.commerce_refund_requests(id) on delete cascade,
  from_status text,
  to_status text not null,
  event_type text not null,
  actor_user_id uuid references public.platform_users(id) on delete set null,
  details jsonb not null default '{}'::jsonb,
  created_at timestamptz not null default now()
);

create index if not exists idx_commerce_refunds_order
  on public.commerce_refund_requests(tenant_id, order_id, created_at desc);

create index if not exists idx_commerce_refunds_status
  on public.commerce_refund_requests(tenant_id, status, created_at desc);

create index if not exists idx_commerce_refund_events_request
  on public.commerce_refund_events(tenant_id, refund_request_id, created_at desc);

alter table public.commerce_refund_requests enable row level security;
alter table public.commerce_refund_events enable row level security;

drop policy if exists tenant_isolation on public.commerce_refund_requests;
create policy tenant_isolation on public.commerce_refund_requests
  for all
  using (tenant_id = app.current_tenant_id() or app.is_platform_admin())
  with check (tenant_id = app.current_tenant_id() or app.is_platform_admin());

drop policy if exists tenant_isolation on public.commerce_refund_events;
create policy tenant_isolation on public.commerce_refund_events
  for all
  using (tenant_id = app.current_tenant_id() or app.is_platform_admin())
  with check (tenant_id = app.current_tenant_id() or app.is_platform_admin());

drop trigger if exists set_updated_at on public.commerce_refund_requests;
create trigger set_updated_at
  before update on public.commerce_refund_requests
  for each row execute function app.touch_updated_at();
