import {
  db,
  type TailorAnyDBField,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { item as itemStub } from "../lib/_db_deps";
import { inventoryCount } from "./inventoryCount";
import { storageLocation } from "./storageLocation";

export const BASE_COUNT_LINE_STATUSES = ["PENDING", "APPROVED", "REJECTED", "RECOUNT"] as const;

export interface CreateInventoryCountLineTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
}

export function createInventoryCountLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateInventoryCountLineTypeParams<F>,
) {
  return db
    .type("InventoryCountLine", {
      inventoryCountId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: inventoryCount },
          backward: "countLines",
        })
        .description("Foreign key to InventoryCount"),
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: itemStub },
          backward: "inventoryCountLines",
        })
        .description("Foreign key to Item"),
      storageLocationId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: storageLocation },
          backward: "inventoryCountLines",
        })
        .description("Foreign key to StorageLocation"),
      systemQuantity: db.float().description("System quantity snapshot at count start"),
      countedQuantity: db.float({ optional: true }).description("Physically counted quantity"),
      variance: db
        .float({ optional: true })
        .description("Computed variance: countedQuantity - systemQuantity"),
      status: db
        .enum([...BASE_COUNT_LINE_STATUSES] as [string, ...string[]])
        .description("Review status: PENDING, APPROVED, REJECTED, RECOUNT"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const inventoryCountLine = createInventoryCountLineType({});
