create table if not exists public.commerce_bill_download_jobs (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null references public.tenants(id) on delete cascade,
  provider text not null
    check (provider in ('wechat_pay', 'alipay')),
  bill_date date not null,
  bill_type text not null default 'payment'
    check (bill_type in ('payment', 'refund', 'combined')),
  status text not null default 'queued'
    check (status in ('queued', 'running', 'completed', 'failed', 'cancelled')),
  source_name text not null,
  source_hash text,
  row_count integer not null default 0 check (row_count >= 0),
  download_hash_type text,
  download_hash_value text,
  download_url_host text,
  reconciliation_batch_id uuid references public.commerce_reconciliation_batches(id) on delete set null,
  requested_by uuid references public.platform_users(id) on delete set null,
  claimed_by text,
  claimed_at timestamptz,
  completed_at timestamptz,
  failed_at timestamptz,
  error_code text,
  error_message text,
  metadata jsonb not null default '{}'::jsonb,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

create unique index if not exists idx_commerce_bill_download_jobs_idempotency
  on public.commerce_bill_download_jobs(tenant_id, provider, bill_date, bill_type)
  where status in ('queued', 'running', 'completed');

create index if not exists idx_commerce_bill_download_jobs_claim
  on public.commerce_bill_download_jobs(status, created_at)
  where status = 'queued';

create index if not exists idx_commerce_bill_download_jobs_tenant
  on public.commerce_bill_download_jobs(tenant_id, provider, bill_date desc, created_at desc);

create index if not exists idx_commerce_bill_download_jobs_batch
  on public.commerce_bill_download_jobs(tenant_id, reconciliation_batch_id)
  where reconciliation_batch_id is not null;

alter table public.commerce_bill_download_jobs enable row level security;

drop policy if exists tenant_isolation on public.commerce_bill_download_jobs;
create policy tenant_isolation on public.commerce_bill_download_jobs
  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_bill_download_jobs;
create trigger set_updated_at
  before update on public.commerce_bill_download_jobs
  for each row execute function app.touch_updated_at();
