import {
  TaxCode as CwTaxCode,
  TaxCodeLevel as CwTaxCodeLevel,
} from "../../generated/prisma/client";
import { TaxCode as ApiTaxCode } from "../../../api/generated/prisma/client";
import { Translation } from "./types";
import { skipRow } from "./types";

type CwTaxCodeWithLevels = CwTaxCode & {
  levels: CwTaxCodeLevel[];
};

export const taxCodeTranslation: Translation<
  CwTaxCodeWithLevels,
  ApiTaxCode
> = {
  values: [
    { from: "taxCodeRecId", to: "id" },
    {
      from: "taxCodeId",
      to: "code",
      process: (value) => value ?? skipRow("taxCodeId is null"),
    },
    {
      from: "codeCaption",
      to: "codeCaption",
      process: (value, _, row) =>
        value ?? (row.taxCodeId as string | null) ?? "",
    },
    { from: "description", to: "description" },
    {
      from: "taxCodeRecId",
      to: "rate",
      process: (_, __, row) => {
        const level = (row as unknown as CwTaxCodeWithLevels).levels.find(
          (l) => l.taxXref !== null
        );
        return level ? Number(level.taxRate) : null;
      },
    },
    { from: "defaultFlag", to: "defaultFlag" },
    { from: "enteredBy", to: "createdBy" },
    { from: "updatedBy", to: "updatedBy" },
    { from: "dateEnteredUtc", to: "createdAt" },
    { from: "lastUpdatedUtc", to: "updatedAt" },
  ],
};
