create table if not exists data_service_requests (
  id uuid primary key default gen_random_uuid(),
  request_no text not null unique,
  user_id uuid not null references users(id) on delete cascade,
  order_id uuid unique references orders(id) on delete set null,
  status text not null default 'pending_contact',
  current_step integer not null default 1,
  company text not null default '',
  organization_type text not null default '',
  contact_name text not null default '',
  contact_phone text not null default '',
  email text not null default '',
  city text not null default '',
  data_topic text not null default '',
  service_type text not null default '',
  region_scope text not null default '',
  time_range text not null default '',
  industry_scene text not null default '',
  expected_format text not null default '',
  data_volume text not null default '',
  usage_purpose text not null default '',
  requirement text not null default '',
  expected_result text not null default '',
  deadline text not null default '',
  budget_range text not null default '',
  sensitive_data boolean not null default false,
  preferred_contact_time text not null default '',
  extra_note text not null default '',
  assigned_account_id uuid references staff_accounts(id) on delete set null,
  contact_note text not null default '',
  progress_note text not null default '',
  quoted_title text not null default '',
  quoted_amount integer not null default 0,
  quoted_note text not null default '',
  quoted_at timestamptz,
  paid_at timestamptz,
  deliverable_file_id uuid references uploaded_files(id) on delete set null,
  result_summary text not null default '',
  completed_at timestamptz,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

create index if not exists idx_data_service_requests_user_created
  on data_service_requests(user_id, created_at desc);
create index if not exists idx_data_service_requests_status
  on data_service_requests(status, updated_at desc);
create index if not exists idx_data_service_requests_assignee
  on data_service_requests(assigned_account_id, status, updated_at desc);
create index if not exists idx_data_service_requests_order
  on data_service_requests(order_id);

insert into products (id, slug, type, title, summary, price_amount, purchase_flow, fulfillment_flow, status)
values (
  'data-service-custom',
  'data-service-custom',
  'data',
  '定制数据服务',
  '根据用户申请、业务沟通和报价确认整理的数据包交付服务。',
  0,
  'application',
  'download',
  'published'
)
on conflict (id) do update set
  slug = excluded.slug,
  type = excluded.type,
  title = excluded.title,
  summary = excluded.summary,
  price_amount = excluded.price_amount,
  purchase_flow = excluded.purchase_flow,
  fulfillment_flow = excluded.fulfillment_flow,
  status = excluded.status,
  updated_at = now();
