import refreshTokenHelper from "../../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../../utils/errorHandlingHelper"
import { buildImportPreview, importRows, type ImportRowInput } from "../../../../utils/listings/importer"
import { eventFetch } from "../../../../utils/listings/listingStore"

// POST /api/sales/sms/listings/import
//   { orderSourceId, rows: ImportRowInput[] (≤ 500), overwriteExisting?, createProducts?, importImages? }
//   { orderSourceId, all: true, overwriteExisting?, refresh?, createProducts?, importImages? }
// createProducts: rows without a matched product get a minimal M_Product (Value = SKU, asin, Amazon price);
// importImages: the ASIN's MAIN catalog picture goes to the product when it has no image in Strapi yet.
const handleFunc = async (event: any, authToken: any = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event).catch(() => ({}))
  const orderSourceId = Number(body?.orderSourceId)
  if (!orderSourceId) return { status: 400, message: 'orderSourceId is required' }
  const f = eventFetch(event, token)
  const orderSource: any = await f(`models/c_ordersource/${orderSourceId}`)
  if (!orderSource?.id) return { status: 404, message: 'Order source not found' }

  let rows: ImportRowInput[] = Array.isArray(body?.rows) ? body.rows : []
  if (body?.all === true) {
    const preview = await buildImportPreview(event, token, f, orderSource, { forceRefresh: !!body?.refresh })
    if (preview.pending) return { status: 202, pending: true, orderSourceId, startedAt: preview.startedAt, message: 'Amazon is still generating the listings report' }
    rows = preview.rows
  }
  if (!rows.length) return { status: 400, message: 'rows[] is empty (or pass all: true)' }
  if (rows.length > 500 && body?.all !== true) return { status: 400, message: 'at most 500 rows per call' }
  const result = await importRows(f, orderSource, rows, {
    overwriteExisting: body?.overwriteExisting === true,
    createProducts: body?.createProducts === true,
    importImages: body?.importImages === true,
    salesRepId: Number(getCookie(event, 'logship_user_id')) || null
  })
  return { status: 200, orderSourceId, requested: rows.length, ...result }
}

export default defineEventHandler(async (event) => {
  let data: any = {}
  try {
    data = await handleFunc(event)
  } catch (err: any) {
    if (err?.isAmazonError) return errorHandlingHelper(err?.data ?? err, err?.data ?? err)
    try {
      const authToken: any = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch (error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }
  return data
})
