import type { RouteLaneImportPreviewRow } from "@/app/api/shop/client";
import type { TruckLaneMoveTargetRequest } from "@/app/api/shop/actions";
import { normalizeStoreId } from "@/app/utils/formatUtil";

export type ScheduleRouteExcelRowError = {
  shopCode: string;
  shopName: string;
  message: string;
};

export type ScheduleRouteExcelMovePreview = {
  truckRowId: number;
  shopCode: string;
  shopName: string;
  toTruckLanceCode: string;
  toRemark: string | null;
  toStoreId: string;
  toLoadingSequence: number;
};

export type ScheduleRouteExcelToMovesResult = {
  moves: TruckLaneMoveTargetRequest[];
  previews: ScheduleRouteExcelMovePreview[];
  rowErrors: ScheduleRouteExcelRowError[];
};

export function formatScheduleTargetLaneLabel(
  truckLanceCode: string,
  remark: string | null | undefined,
): string {
  const code = String(truckLanceCode || "").trim();
  const rem = remark != null && String(remark).trim() !== "" ? String(remark).trim() : "";
  return rem ? `${code} (${rem})` : code;
}

/**
 * Converts RouteBoard MTMS Excel parse rows into truck-lane schedule moves.
 * Rows without an existing truck board row are reported as errors.
 */
export function scheduleRouteExcelToMoves(
  rows: RouteLaneImportPreviewRow[],
): ScheduleRouteExcelToMovesResult {
  const moves: TruckLaneMoveTargetRequest[] = [];
  const previews: ScheduleRouteExcelMovePreview[] = [];
  const rowErrors: ScheduleRouteExcelRowError[] = [];

  for (const row of rows) {
    const shopCode = String(row.shopCode || "").trim() || "-";
    const shopName = String(row.shopName || "").trim() || "-";
    const truckRowId = row.truckRowId;

    if (truckRowId == null || !Number.isFinite(truckRowId) || truckRowId <= 0) {
      rowErrors.push({
        shopCode,
        shopName,
        message: "no_truck_row",
      });
      continue;
    }

    const toTruckLanceCode = String(row.truckLanceCode || "").trim();
    if (!toTruckLanceCode) {
      rowErrors.push({
        shopCode,
        shopName,
        message: "no_target_lane",
      });
      continue;
    }

    const toRemark =
      row.remark != null && String(row.remark).trim() !== ""
        ? String(row.remark).trim()
        : null;
    const toStoreId = normalizeStoreId(row.storeId);
    const seq = Math.max(0, Number(row.loadingSequence ?? 0) || 0);

    const move: TruckLaneMoveTargetRequest = {
      truckRowId,
      toTruckLanceCode,
      toRemark,
      toStoreId,
      toLoadingSequence: seq,
      toDistrictReference: row.districtReference ?? null,
    };
    moves.push(move);
    previews.push({
      truckRowId,
      shopCode,
      shopName,
      toTruckLanceCode,
      toRemark,
      toStoreId,
      toLoadingSequence: seq,
    });
  }

  return { moves, previews, rowErrors };
}
