import { type EmptyFields, type FieldsToInsertable } from "@tailor-platform/erp-kit/core";
import { type TailorAnyDBField } from "@tailor-platform/sdk";
import type { defineModule as defineItemManagementModule } from "../item-management";
import type { defineModule as defineOrganizationModule } from "../organization";
import type { defineModule as definePrimitivesModule } from "../primitives";
import { assignSerialNumber } from "./command/assignSerialNumber.generated";
import { cancelGoodsIssue } from "./command/cancelGoodsIssue.generated";
import { cancelGoodsReceipt } from "./command/cancelGoodsReceipt.generated";
import { cancelStockAdjustment } from "./command/cancelStockAdjustment.generated";
import { closeInventorySupplyPlan } from "./command/closeInventorySupplyPlan.generated";
import { closeStockReservation } from "./command/closeStockReservation.generated";
import { closeTransferOrder } from "./command/closeTransferOrder.generated";
import { confirmStockAdjustment } from "./command/confirmStockAdjustment.generated";
import { createGoodsIssue } from "./command/createGoodsIssue.generated";
import { createGoodsReceipt } from "./command/createGoodsReceipt.generated";
import { createInventorySupplyPlan } from "./command/createInventorySupplyPlan.generated";
import { createLot } from "./command/createLot.generated";
import { createStockAdjustment } from "./command/createStockAdjustment.generated";
import { createStockReservation } from "./command/createStockReservation.generated";
import { createStorageLocation } from "./command/createStorageLocation.generated";
import { createTransferOrder } from "./command/createTransferOrder.generated";
import { createValuationPolicy } from "./command/createValuationPolicy.generated";
import { deactivateStorageLocation } from "./command/deactivateStorageLocation.generated";
import { openTransferOrder } from "./command/openTransferOrder.generated";
import { postGoodsIssue } from "./command/postGoodsIssue.generated";
import { postGoodsReceipt } from "./command/postGoodsReceipt.generated";
import { reactivateStorageLocation } from "./command/reactivateStorageLocation.generated";
import { receiveTransferOrder } from "./command/receiveTransferOrder.generated";
import { rejectStockAdjustment } from "./command/rejectStockAdjustment.generated";
import { shipTransferOrder } from "./command/shipTransferOrder.generated";
import { submitStockAdjustment } from "./command/submitStockAdjustment.generated";
import { updateGoodsIssue } from "./command/updateGoodsIssue.generated";
import { updateGoodsReceipt } from "./command/updateGoodsReceipt.generated";
import { updateInventorySupplyPlan } from "./command/updateInventorySupplyPlan.generated";
import { updateLot } from "./command/updateLot.generated";
import { updateStockAdjustment } from "./command/updateStockAdjustment.generated";
import { updateStockReservation } from "./command/updateStockReservation.generated";
import { updateStorageLocation } from "./command/updateStorageLocation.generated";
import { updateTransferOrder } from "./command/updateTransferOrder.generated";
import { updateValuationPolicy } from "./command/updateValuationPolicy.generated";
import { createCostLayerType } from "./db/costLayer";
import {
  createInventoryExecutionType,
  type CreateInventoryExecutionTypeParams,
} from "./db/inventoryExecution";
import {
  createInventoryExecutionLineType,
  type CreateInventoryExecutionLineTypeParams,
} from "./db/inventoryExecutionLine";
import { createInventoryLedgerType } from "./db/inventoryLedger";
import {
  createInventorySupplyPlanType,
  type CreateInventorySupplyPlanTypeParams,
} from "./db/inventorySupplyPlan";
import { createItemValuationType } from "./db/itemValuation";
import { createLotType } from "./db/lot";
import { createLotStockLevelType } from "./db/lotStockLevel";
import { createSerialNumberType } from "./db/serialNumber";
import { createStockAdjustmentType } from "./db/stockAdjustment";
import { createStockAdjustmentLineType } from "./db/stockAdjustmentLine";
import { createStockLevelType } from "./db/stockLevel";
import { createStockReservationType } from "./db/stockReservation";
import {
  createStorageLocationType,
  type CreateStorageLocationTypeParams,
} from "./db/storageLocation";
import { createTransferOrderType, type CreateTransferOrderTypeParams } from "./db/transferOrder";
import {
  createTransferOrderLineType,
  type CreateTransferOrderLineTypeParams,
} from "./db/transferOrderLine";
import { createValuationPolicyType } from "./db/valuationPolicy";
import { getGoodsIssue } from "./query/getGoodsIssue.generated";
import { getGoodsReceipt } from "./query/getGoodsReceipt.generated";
import { getInventorySupplyPlan } from "./query/getInventorySupplyPlan.generated";
import { getItemValuation } from "./query/getItemValuation.generated";
import { getLot } from "./query/getLot.generated";
import { getSerialNumber } from "./query/getSerialNumber.generated";
import { getSerialNumberHistory } from "./query/getSerialNumberHistory.generated";
import { getSiteStockSummary } from "./query/getSiteStockSummary.generated";
import { getStockAdjustment } from "./query/getStockAdjustment.generated";
import { getStockLevel } from "./query/getStockLevel.generated";
import { getStorageLocation } from "./query/getStorageLocation.generated";
import { getTransferOrder } from "./query/getTransferOrder.generated";
import { getValuationPolicy } from "./query/getValuationPolicy.generated";
import { listCostLayers } from "./query/listCostLayers.generated";
import { listExpiringLots } from "./query/listExpiringLots.generated";
import { listGoodsIssues } from "./query/listGoodsIssues.generated";
import { listGoodsReceipts } from "./query/listGoodsReceipts.generated";
import { listInventorySupplyPlans } from "./query/listInventorySupplyPlans.generated";
import { listItemValuations } from "./query/listItemValuations.generated";
import { listLots } from "./query/listLots.generated";
import { listPurchaseReceiptEvidenceForMatching } from "./query/listPurchaseReceiptEvidenceForMatching.generated";
import { listPurchaseReceiptQuantitiesForMatching } from "./query/listPurchaseReceiptQuantitiesForMatching.generated";
import { listSerialNumbers } from "./query/listSerialNumbers.generated";
import { listStockAdjustments } from "./query/listStockAdjustments.generated";
import { listStockLevels } from "./query/listStockLevels.generated";
import { listStorageLocations } from "./query/listStorageLocations.generated";
import { listTransferOrders } from "./query/listTransferOrders.generated";
import { listValuationPolicies } from "./query/listValuationPolicies.generated";
import { traceLotBackward } from "./query/traceLotBackward.generated";
import { traceLotForward } from "./query/traceLotForward.generated";

type OrganizationModule = ReturnType<typeof defineOrganizationModule>;
type OrganizationDB = OrganizationModule["db"];
export type OrganizationQueries = OrganizationModule["queries"];

type ItemManagementModule = ReturnType<typeof defineItemManagementModule>;
type ItemManagementDB = ItemManagementModule["db"];
export type ItemManagementQueries = ItemManagementModule["queries"];

type PrimitivesModule = ReturnType<typeof definePrimitivesModule>;
type PrimitivesDB = PrimitivesModule["db"];

export interface DefineModuleParams<
  SF extends Record<string, TailorAnyDBField> = EmptyFields,
  ISPF extends Record<string, TailorAnyDBField> = EmptyFields,
  TOF extends Record<string, TailorAnyDBField> = EmptyFields,
  TOLF extends Record<string, TailorAnyDBField> = EmptyFields,
  IEF extends Record<string, TailorAnyDBField> = EmptyFields,
  IELF extends Record<string, TailorAnyDBField> = EmptyFields,
> {
  storageLocation?: Omit<CreateStorageLocationTypeParams<SF>, "siteType">;
  inventorySupplyPlan?: Omit<CreateInventorySupplyPlanTypeParams<ISPF>, "itemType" | "siteType">;
  transferOrder?: Omit<CreateTransferOrderTypeParams<TOF>, "siteType">;
  transferOrderLine?: Omit<CreateTransferOrderLineTypeParams<TOLF>, "itemType" | "unitType">;
  inventoryExecution?: CreateInventoryExecutionTypeParams<IEF>;
  inventoryExecutionLine?: Omit<CreateInventoryExecutionLineTypeParams<IELF>, "unitType">;
  organization: {
    db: { site: OrganizationDB["site"] };
    queries: { getSite: OrganizationQueries["getSite"] };
  };
  itemManagement: {
    db: { item: ItemManagementDB["item"] };
    queries: { getItem: ItemManagementQueries["getItem"] };
  };
  primitives: {
    db: { unit: PrimitivesDB["unit"] };
  };
}

/* @__NO_SIDE_EFFECTS__ */
export const defineModule = <
  const SF extends Record<string, TailorAnyDBField> = EmptyFields,
  const ISPF extends Record<string, TailorAnyDBField> = EmptyFields,
  const TOF extends Record<string, TailorAnyDBField> = EmptyFields,
  const TOLF extends Record<string, TailorAnyDBField> = EmptyFields,
  const IEF extends Record<string, TailorAnyDBField> = EmptyFields,
  const IELF extends Record<string, TailorAnyDBField> = EmptyFields,
>(
  params: DefineModuleParams<SF, ISPF, TOF, TOLF, IEF, IELF>,
) => {
  const storageLocation = createStorageLocationType({
    ...params.storageLocation,
    siteType: params.organization.db.site,
  });
  const valuationPolicy = createValuationPolicyType({});
  const stockLevel = createStockLevelType({ itemType: params.itemManagement.db.item });
  const stockReservation = createStockReservationType({
    itemType: params.itemManagement.db.item,
    siteType: params.organization.db.site,
  });
  const inventorySupplyPlan = createInventorySupplyPlanType({
    ...params.inventorySupplyPlan,
    itemType: params.itemManagement.db.item,
    siteType: params.organization.db.site,
  });
  const stockAdjustment = createStockAdjustmentType({});
  const stockAdjustmentLine = createStockAdjustmentLineType({
    itemType: params.itemManagement.db.item,
  });
  const lot = createLotType({ itemType: params.itemManagement.db.item });
  const lotStockLevel = createLotStockLevelType({});
  const serialNumber = createSerialNumberType({ itemType: params.itemManagement.db.item });
  const transferOrder = createTransferOrderType({
    ...params.transferOrder,
    siteType: params.organization.db.site,
  });
  const transferOrderLine = createTransferOrderLineType({
    ...params.transferOrderLine,
    itemType: params.itemManagement.db.item,
    unitType: params.primitives.db.unit,
  });
  const inventoryExecution = createInventoryExecutionType({
    ...params.inventoryExecution,
  });
  const inventoryExecutionLine = createInventoryExecutionLineType({
    ...params.inventoryExecutionLine,
    itemType: params.itemManagement.db.item,
    unitType: params.primitives.db.unit,
  });
  const inventoryLedger = createInventoryLedgerType({ itemType: params.itemManagement.db.item });
  const itemValuation = createItemValuationType({ itemType: params.itemManagement.db.item });
  const costLayer = createCostLayerType({ itemType: params.itemManagement.db.item });

  const orgQueries = params.organization.queries;
  const itemQueries = params.itemManagement.queries;

  return {
    db: {
      storageLocation,
      valuationPolicy,
      stockLevel,
      stockReservation,
      inventorySupplyPlan,
      stockAdjustment,
      stockAdjustmentLine,
      transferOrder,
      transferOrderLine,
      inventoryExecution,
      inventoryExecutionLine,
      inventoryLedger,
      lot,
      lotStockLevel,
      serialNumber,
      itemValuation,
      costLayer,
    },
    queries: {
      getStorageLocation,
      getValuationPolicy,
      getStockLevel,
      getInventorySupplyPlan,
      getStockAdjustment,
      getTransferOrder,
      getGoodsReceipt,
      getGoodsIssue,
      getLot,
      getSerialNumber,
      getSerialNumberHistory,
      getItemValuation,
      getSiteStockSummary,
      listStorageLocations,
      listValuationPolicies,
      listStockLevels,
      listGoodsReceipts,
      listPurchaseReceiptEvidenceForMatching,
      listPurchaseReceiptQuantitiesForMatching,
      listGoodsIssues,
      listInventorySupplyPlans,
      listStockAdjustments,
      listTransferOrders,
      listLots,
      listSerialNumbers,
      listItemValuations,
      listCostLayers,
      listExpiringLots,
      traceLotForward,
      traceLotBackward,
    },
    commands: {
      createStorageLocation: createStorageLocation<FieldsToInsertable<SF>>(orgQueries),
      updateStorageLocation: updateStorageLocation(),
      deactivateStorageLocation: deactivateStorageLocation(),
      reactivateStorageLocation: reactivateStorageLocation(orgQueries),
      createValuationPolicy: createValuationPolicy(),
      updateValuationPolicy: updateValuationPolicy(),
      createLot: createLot(itemQueries),
      updateLot: updateLot(),
      assignSerialNumber: assignSerialNumber(itemQueries),
      createGoodsIssue: createGoodsIssue<FieldsToInsertable<IEF>, FieldsToInsertable<IELF>>(
        itemQueries,
      ),
      updateGoodsIssue: updateGoodsIssue<FieldsToInsertable<IEF>, FieldsToInsertable<IELF>>(
        itemQueries,
      ),
      cancelGoodsIssue: cancelGoodsIssue(),
      postGoodsIssue: postGoodsIssue(itemQueries),
      createGoodsReceipt: createGoodsReceipt<FieldsToInsertable<IEF>, FieldsToInsertable<IELF>>(
        itemQueries,
      ),
      updateGoodsReceipt: updateGoodsReceipt<FieldsToInsertable<IEF>, FieldsToInsertable<IELF>>(
        itemQueries,
      ),
      cancelGoodsReceipt: cancelGoodsReceipt(),
      postGoodsReceipt: postGoodsReceipt(itemQueries),
      createInventorySupplyPlan: createInventorySupplyPlan<FieldsToInsertable<ISPF>>(
        itemQueries,
        orgQueries,
      ),
      updateInventorySupplyPlan: updateInventorySupplyPlan<FieldsToInsertable<ISPF>>(
        itemQueries,
        orgQueries,
      ),
      closeInventorySupplyPlan: closeInventorySupplyPlan(),
      createStockAdjustment: createStockAdjustment(itemQueries),
      updateStockAdjustment: updateStockAdjustment(itemQueries),
      submitStockAdjustment: submitStockAdjustment(itemQueries),
      confirmStockAdjustment: confirmStockAdjustment(itemQueries),
      rejectStockAdjustment: rejectStockAdjustment(),
      cancelStockAdjustment: cancelStockAdjustment(),
      closeStockReservation: closeStockReservation(),
      createStockReservation: createStockReservation(itemQueries, orgQueries),
      updateStockReservation: updateStockReservation(itemQueries, orgQueries),
      createTransferOrder: createTransferOrder<FieldsToInsertable<TOF>, FieldsToInsertable<TOLF>>(
        itemQueries,
        orgQueries,
      ),
      updateTransferOrder: updateTransferOrder<FieldsToInsertable<TOF>, FieldsToInsertable<TOLF>>(
        itemQueries,
        orgQueries,
      ),
      openTransferOrder: openTransferOrder(),
      shipTransferOrder: shipTransferOrder(),
      receiveTransferOrder: receiveTransferOrder(),
      closeTransferOrder: closeTransferOrder(),
    },
  };
};
