import type { KbxIntegrationProblem } from '@kbx/contracts'
import type { WmsWorkRow } from './work.definition'

export interface WmsWorkSearch { taskType?: string; status?: string; owner?: string; keyword?: string }
export interface WmsWorkSearchSummary { totalCount:number; readyCount:number; inProgressCount:number; blockedCount:number }
export interface WmsWorkSearchResult { items:WmsWorkRow[]; totalCount:number; summary:WmsWorkSearchSummary }

const demoRows:WmsWorkRow[]=[
  {taskId:'41000000-0000-4000-8000-000000000001',taskNo:'RCV-260811-001',taskType:'RECEIVING',waveNo:'ASN-260811-001',ownerName:'QA 사용자',progress:0,totalLines:3,completedLines:0,slaAt:'2026-08-11T23:40:00+09:00',status:'READY',exceptionCount:0},
  {taskId:'42000000-0000-4000-8000-000000000001',taskNo:'PUT-260811-004',taskType:'PUTAWAY',waveNo:'PUT-260811-A',ownerName:'QA 사용자',progress:33,totalLines:3,completedLines:1,slaAt:'2026-08-12T00:10:00+09:00',status:'IN_PROGRESS',exceptionCount:0},
  {taskId:'30000000-0000-4000-8000-000000000001',taskNo:'PICK-260811-001',taskType:'PICKING',waveNo:'W260811-01',ownerName:'QA 사용자',progress:17,totalLines:138,completedLines:23,slaAt:'2026-08-11T23:30:00+09:00',status:'READY',exceptionCount:0},
  {taskId:'43000000-0000-4000-8000-000000000001',taskNo:'CNT-260811-002',taskType:'COUNTING',waveNo:'COUNT-A',ownerName:'QA 사용자',progress:50,totalLines:8,completedLines:4,slaAt:'2026-08-12T00:30:00+09:00',status:'IN_PROGRESS',exceptionCount:1},
  {taskId:'30000000-0000-4000-8000-000000000009',taskNo:'PICK-260811-009',taskType:'PICKING',waveNo:'W260811-03',ownerName:'QA 사용자',progress:42,totalLines:62,completedLines:26,slaAt:'2026-08-11T23:20:00+09:00',status:'BLOCKED',exceptionCount:2},
]

function matchesBase(row:WmsWorkRow, search:WmsWorkSearch){
  if(search.taskType&&row.taskType!==search.taskType)return false
  if(search.owner==='mine'&&row.ownerName!=='QA 사용자')return false
  if(search.owner==='unassigned'&&row.ownerName)return false
  const keyword=String(search.keyword??'').trim().toLocaleLowerCase()
  if(keyword&&!`${row.taskNo} ${row.waveNo??''} ${row.ownerName??''} ${row.taskType}`.toLocaleLowerCase().includes(keyword))return false
  return true
}
function matches(row:WmsWorkRow, search:WmsWorkSearch){
  return matchesBase(row,search)&&(!search.status||row.status===search.status)
}

/**
 * The work queue must never pretend that an unconnected production query returned an empty set.
 * Demo mode provides browser-only fixtures so the FE workflow can be exercised without BE coupling.
 */
export async function searchWmsWork(search: WmsWorkSearch): Promise<WmsWorkSearchResult> {
  if(import.meta.env.VITE_KBX_DEMO_MODE==='true'){
    await new Promise(resolve=>setTimeout(resolve,90))
    const summaryRows=demoRows.filter(row=>matchesBase(row,search))
    const items=demoRows.filter(row=>matches(row,search)).map(row=>({...row}))
    return {
      items,
      totalCount:items.length,
      summary:{
        totalCount:summaryRows.length,
        readyCount:summaryRows.filter(row=>row.status==='READY').length,
        inProgressCount:summaryRows.filter(row=>row.status==='IN_PROGRESS').length,
        blockedCount:summaryRows.filter(row=>row.status==='BLOCKED').length,
      },
    }
  }
  const problem:KbxIntegrationProblem={
    type:'integration',
    code:'WMS_WORK_QUERY_NOT_CONNECTED',
    title:'물류 작업 조회를 연결할 수 없습니다.',
    detail:'운영 WMS 작업조회 API가 연결되기 전에는 빈 작업목록으로 가장하지 않습니다. 연결 상태를 확인한 후 다시 조회하세요.',
    retryable:false,
  }
  throw problem
}

export function routeForWmsTask(row: WmsWorkRow): string {
  switch (row.taskType) {
    case 'RECEIVING': return `/wms/receiving/${row.taskId}`
    case 'PUTAWAY': return `/wms/putaway/${row.taskId}`
    case 'PICKING': return `/wms/picking/${row.taskId}`
    case 'COUNTING': return `/wms/counting/${row.taskId}`
    default: return `/wms/work?task=${encodeURIComponent(row.taskId)}`
  }
}
