export interface ProcurementMaterial {
  id: string;
  material_name: string;
  specification: string;
  quantity: number;
  unit: string;
  technical_standard: string;
  material_requirement: string;
  technical_requirement: string;
  applicable_conditions: string;
  test_requirement: string;
  acceptance_note: string;
  warranty_period: string;
  deadline: string;
  invoice_type: string;
  brand: string;
  remarks: string;
  delivery_address: string;
  source_file: string;
  source_file_id?: string;
  batch_id: string;
  created_at: string;
  created_by?: string;
}

export interface StandardizedMaterial {
  id: string;
  batch_id: string;
  material_id: string;
  source_type?: 'ai' | 'manual';
  invoice_type: string;
  original_name: string;
  original_spec: string;
  standardized_name: string;
  category: string;
  brand: string;
  notes: string;
  delivery_address: string;
  primary_search_term: string;
  alt_search_terms: string[];
  standardized_spec: string;
  standardized_unit: string;
  quantity: number;
  product_type: string;
  llm_model: string;
  ai_reasoning: string;
  created_by?: string | null;
  updated_at?: string;
  created_at: string;
}

export interface SearchResult {
  id: string;
  task_id?: string | null;
  batch_id: string;
  keyword: string;
  material_id: string;
  material_name?: string;
  standardized_name?: string;
  result_index: number;
  title: string;
  price: string;
  offer_url: string;
  image_url: string;
  screenshot_path: string;
  screenshot_public_url: string;
  merchant_name: string;
  merchant_url: string;
  contact_type: string;
  contact_url: string;
  contact_handle: string;
  contact_site: string;
  contact_page_url: string;
  contact_person: string;
  phone: string;
  mobile: string;
  address: string;
  image_error: string;
  created_at: string;
  score?: number | null;
  is_match?: boolean | null;
  reason?: string;
  keyword_hit_rate?: number | null;
  stage_order?: number | null;
  stage_label?: string;
  stage_kind?: string;
  stage_main_keyword?: string;
  stage_keyword_hit_rate?: number | null;
  is_placeholder?: boolean;
  placeholder_reason?: string;
  has_phone_contact?: boolean;
  qualification_status?: string;
  contact_collection_reason?: string;
}

export interface SearchStageSummary {
  id: string;
  task_id?: string | null;
  batch_id: string;
  material_id: string;
  stage_order: number;
  stage_label: string;
  stage_kind: string;
  stage_main_keyword: string;
  keyword_hit_rate?: number | null;
  source_candidate_count?: number | null;
  shortage_reason?: string;
  require_phone_contact?: boolean;
  stop_reason?: string;
  contact_enrichment_skip_reason?: string;
  stage_started_at?: string | null;
  stage_ended_at?: string | null;
  stage_duration_ms?: number | null;
  stage_status?: string;
  created_at: string;
}

export interface ContactLog {
  id: string;
  batch_id: string;
  search_result_id: string;
  keyword: string;
  merchant_name: string;
  title: string;
  offer_url: string;
  contact_url: string;
  message_sent: string;
  status: 'sent' | 'skipped' | 'error' | 'unknown';
  reason: string;
  final_url: string;
  conversation_code: string;
  created_at: string;
}

export interface MerchantContact {
  id: string;
  merchant_url: string;
  merchant_name: string;
  contact_page_url: string;
  standardized_name?: string;
  contact_person: string;
  phone: string;
  mobile: string;
  address: string;
  source_batch_id: string;
  source_offer_url: string;
  created_at: string;
  updated_at: string;
  updated_by: string;
}

export interface ChatMessage {
  role: 'self' | 'other' | 'system';
  content: string;
}

export interface CustomerServiceChat {
  id: string;
  product_url: string;
  batch_id?: string;
  search_result_id?: string;
  contact_url?: string;
  merchant_name?: string;
  title?: string;
  current_round?: number;
  status?: string;
  last_interacted_at?: string | null;
  chat_history: ChatMessage[];
  created_at: string;
}

export interface ProcurementBatch {
  id: string;
  batch_id: string;
  name: string | null;
  archived: boolean;
  created_by: string | null;
  created_at: string;
  updated_at: string;
}

export interface BatchSummary {
  batch_id: string;
  name: string | null;
  archived: boolean;
  created_at: string;
  materialsCount: number;
  standardizedCount: number;
  searchResultsCount: number;
  contactLogsCount: number;
  sourceFilesCount?: number;
  stage: number; // 1-4
}

export interface SourceFileRecord {
  id: string;
  batch_id: string;
  file_name: string;
  storage_path: string;
  mime_type: string | null;
  size_bytes: number;
  uploaded_by?: string | null;
  uploaded_at: string;
  extraction_status?: SourceFileExtractionStatus | null;
  extraction_model?: string | null;
  extraction_summary?: string | null;
  extraction_error?: string | null;
  extracted_material_count?: number | null;
  extracted_at?: string | null;
}

export type SourceFileExtractionStatus =
  | 'uploaded'
  | 'local_parsed'
  | 'llm_processing'
  | 'llm_succeeded'
  | 'llm_failed';

export interface ColumnDef<T> {
  key: keyof T | string;
  label: string;
  sortable?: boolean;
  render?: (value: unknown, row: T) => React.ReactNode;
  className?: string;
  truncate?: boolean;
}

export type UserRole = 'admin' | 'user';

export interface AuthUser {
  id: string;
  username: string;
  displayName: string;
  email: string;
  role: UserRole;
}

export interface AuthSession {
  token: string;
  user: AuthUser;
  loginAt: string;
}

export interface LoginPayload {
  username: string;
  password: string;
}

export interface RegisterPayload {
  username: string;
  password: string;
}

export interface ChangePasswordPayload {
  currentPassword: string;
  newPassword: string;
}

// ── 智能询价 ─────────────────────────────────────────────

export interface InquiryRoundConfig {
  id: string;
  round: number;
  name: string;
  templateText: string;
  variables: string[];
  passCondition: string;
  enabled: boolean;
}

export interface InquiryBasicImageConfig {
  storagePath: string;
  publicUrl: string;
  name: string;
  mimeType: string;
  sizeBytes: number;
}

export interface InquiryBasicConfig {
  enabled: boolean;
  mode: 'image_round';
  image: InquiryBasicImageConfig;
  sendText: string;
}

export interface InquiryFunnelConfig {
  id: string;
  name: string;
  basicConfig: InquiryBasicConfig;
  rounds: InquiryRoundConfig[];
  activeRoundCount?: number;
  createdAt: string;
  updatedAt: string;
}

export type InquiryTaskStatus =
  | 'PENDING_SEND'
  | 'WAITING_REPLY'
  | `R${number}_PASSED`
  | 'COMPLETED'
  | 'REJECTED'
  | 'TIMEOUT_REJECTED'
  | 'HUMAN_TAKEOVER';

export interface InquiryTask {
  id: string;
  batch_id: string;
  merchant_name: string;
  offer_url: string;
  title: string;
  current_round: number;
  status: InquiryTaskStatus;
  retry_count: number;
  extracted_data: Record<string, unknown> | null;
  ask_context: Record<string, string>;
  chat_history: ChatMessage[];
  created_at: string;
  updated_at: string;
  last_interacted_at: string | null;
}

export type InquiryBatchRunStatus = 'RUNNING' | 'COMPLETED' | 'STOPPED';

export interface InquiryBatchRun {
  id: string;
  batch_id: string;
  account_id: string;
  account_name: string;
  status: InquiryBatchRunStatus;
  total_tasks: number;
  completed_tasks: number;
  rejected_tasks: number;
  started_at: string;
  finished_at: string | null;
}

// ── 1688 Procurement Accounts ────────────────────────────

export interface ProcurementAccount1688 {
  id: string;
  user_id: string;
  account_name: string;
  password: string;
  remark: string | null;
  login_status: string | null;
  login_error: string | null;
  login_checked_at: string | null;
  created_at: string;
  updated_at: string;
}

export interface ProcurementAccount1688CreatePayload {
  account_name: string;
  password: string;
  remark?: string;
}

export interface ProcurementAccount1688UpdatePayload {
  account_name?: string;
  password?: string;
  remark?: string;
}

// ── 采购字典 ─────────────────────────────────────────

export type ProcurementDictionaryTermType = 'unique_model' | 'parameter' | 'brand' | 'standard' | 'general';

export interface ProcurementDictionaryEntry {
  id: string;
  term: string;
  normalized_term?: string;
  term_type: ProcurementDictionaryTermType;
  product_context: string;
  normalized_context?: string;
  interpretation: string;
  suggested_keyword: string;
  evidence: string;
  source_batch_id: string;
  source_material_id: string | null;
  source_llm_model: string;
  occurrence_count: number;
  note: string | null;
  created_by: string | null;
  created_at: string;
  updated_at: string;
}

export interface ProcurementDictionaryCreatePayload {
  term: string;
  term_type: ProcurementDictionaryTermType;
  product_context?: string;
  interpretation: string;
  suggested_keyword?: string;
  evidence?: string;
  note?: string;
}

export interface ProcurementDictionaryUpdatePayload {
  term?: string;
  term_type?: ProcurementDictionaryTermType;
  product_context?: string;
  interpretation?: string;
  suggested_keyword?: string;
  evidence?: string;
  note?: string;
}

// ── 搜索管道配置 ────────────────────────────────────────
// 类型与帮助函数已抽到 `@app/shared-types` workspace，前后端共享 single source of truth。

export {
  DEFAULT_SEARCH_PIPELINE_CONFIG,
  SEARCH_FIELD_LABELS,
  SEARCH_FIELD_ORDER,
  buildKeywordCombinationLabel,
  createDefaultKeywordCombination,
  normalizeKeywordCombination,
  normalizeKeywordCombinationFields,
  normalizeSearchPipelineConfig,
} from '@app/shared-types';
export type {
  KeywordCombination,
  SearchFieldType,
  SearchPipelineConfig,
} from '@app/shared-types';

import {
  normalizeSearchPipelineConfig,
  type SearchPipelineConfig,
} from '@app/shared-types';

export interface SearchPreset {
  id: string;
  user_id: string;
  name: string;
  config: SearchPipelineConfig;
  is_default: boolean;
  created_at: string;
  updated_at: string;
}

export function normalizeSearchPreset(preset: SearchPreset): SearchPreset {
  return {
    ...preset,
    config: normalizeSearchPipelineConfig(preset.config),
  };
}

export const BUILTIN_SEARCH_TEMPLATES: Array<{ id: string; name: string; config: SearchPipelineConfig }> = [
  {
    id: 'default',
    name: '默认（主搜索词递减策略）',
    config: { keywordSearchEnabled: true, imageSearchEnabled: true, keywordCombinations: [], includeAiKeyword: true },
  },
  {
    id: 'name_brand',
    name: '标准化名称+品牌',
    config: { keywordSearchEnabled: true, imageSearchEnabled: true, keywordCombinations: [{ fields: ['standardized_name', 'brand'], label: '标准化名称+品牌' }], includeAiKeyword: true },
  },
  {
    id: 'name_spec',
    name: '标准化名称+标准化规格',
    config: { keywordSearchEnabled: true, imageSearchEnabled: true, keywordCombinations: [{ fields: ['standardized_name', 'standardized_spec'], label: '标准化名称+标准化规格' }], includeAiKeyword: true },
  },
  {
    id: 'name_brand_spec',
    name: '标准化名称+品牌+标准化规格',
    config: { keywordSearchEnabled: true, imageSearchEnabled: true, keywordCombinations: [{ fields: ['standardized_name', 'standardized_spec', 'brand'], label: '标准化名称+标准化规格+品牌' }], includeAiKeyword: true },
  },
  {
    id: 'full',
    name: '主搜索词+标准化名称+品牌+标准化规格',
    config: { keywordSearchEnabled: true, imageSearchEnabled: true, keywordCombinations: [{ fields: ['primary_search_term', 'standardized_name', 'standardized_spec', 'brand'], label: '主搜索词+标准化名称+标准化规格+品牌' }], includeAiKeyword: true },
  },
];

// ── 1688 Search Automation ──────────────────────────────

export interface SearchProgress {
  taskId: string;
  status: 'idle' | 'pending' | 'processing' | 'waiting_for_manual' | 'pausing' | 'paused' | 'stopping' | 'stopped' | 'completed' | 'failed';
  batchId: string;
  accountId: string;
  totalRows: number;
  processedRows: number;
  completedRows: number;
  failedRows: number;
  stoppedRows: number;
  currentRow: string;
  currentItem: string;
  errors: string[];
  result: {
    success?: boolean;
    paused?: boolean;
    stopped?: boolean;
    taskId?: string;
    batchId?: string;
    processedRows?: number;
    totalRows?: number;
    completedRows?: number;
    failedRows?: number;
    stoppedRows?: number;
    errorCount?: number;
    error?: string;
    manualIntervention?: {
      active?: boolean;
      alertId?: string;
      kind?: string;
      message?: string;
      taskId?: string;
      batchId?: string;
      accountId?: string;
      materialId?: string;
      materialName?: string;
      pageUrl?: string;
      detectedAt?: string;
      resolvedAt?: string | null;
      updatedAt?: string;
    };
  } | null;
  startedAt: string | null;
  pausedAt: string | null;
  finishedAt: string | null;
}
