-- Align the legacy Sprint-I fiscal_export_jobs table with the current
-- provider-export workflow. Sprint-T used CREATE IF NOT EXISTS, so an
-- existing legacy table did not receive its newer columns or status/type
-- contract on upgrade.
alter table fiscal_export_jobs
add column if not exists integration_connection_id uuid references integration_connections(id) on delete set null,
add column if not exists provider_export_reference text,
add column if not exists file_asset_id uuid references file_assets(id) on delete set null,
add column if not exists requested_by_user_id uuid references user_accounts(id) on delete set null,
add column if not exists started_at timestamptz,
add column if not exists last_error text;
alter table fiscal_export_jobs
drop constraint if exists fiscal_export_type_check,
drop constraint if exists fiscal_export_status_check;
-- Keep legacy rows readable while allowing the current provider-export names.
alter table fiscal_export_jobs
add constraint fiscal_export_type_check
check(export_type in ('dsfinvk','tse_export','tse','cash_journal')),
add constraint fiscal_export_status_check
check(status in ('queued','pending','processing','running','completed','failed','unsupported'));
alter table fiscal_export_jobs
alter column status set default 'queued';
create index if not exists idx_fiscal_export_jobs_work
on fiscal_export_jobs(status,created_at);
