import { Prisma } from "@prisma/client";

export const SALES_COMMISSION_DIRECTIONS = {
  IN: "IN",
  OUT: "OUT"
} as const;

export const SALES_COMMISSION_SOURCES = {
  CONSIGNMENT_COMMISSION: "CONSIGNMENT_COMMISSION",
  MANUAL_ADJUSTMENT: "MANUAL_ADJUSTMENT",
  OPENING_BALANCE: "OPENING_BALANCE"
} as const;

export type SalesCommissionDirection =
  (typeof SALES_COMMISSION_DIRECTIONS)[keyof typeof SALES_COMMISSION_DIRECTIONS];

export type SalesCommissionSource =
  (typeof SALES_COMMISSION_SOURCES)[keyof typeof SALES_COMMISSION_SOURCES];

function roundAmount(value: number) {
  return Number(value.toFixed(2));
}

export async function createSalesCommissionMutation(
  tx: Prisma.TransactionClient,
  input: {
    salesId: bigint;
    source: SalesCommissionSource;
    direction: SalesCommissionDirection;
    amount: number;
    balanceAfter: number;
    effectiveDate?: Date | null;
    referenceType?: string | null;
    referenceId?: string | null;
    referenceNo?: string | null;
    notes?: string | null;
    metadata?: Prisma.InputJsonValue | null;
  }
) {
  await tx.salesCommissionMutation.create({
    data: {
      salesId: input.salesId,
      source: input.source,
      direction: input.direction,
      amount: new Prisma.Decimal(roundAmount(input.amount)),
      balanceAfter: new Prisma.Decimal(roundAmount(input.balanceAfter)),
      effectiveDate: input.effectiveDate ?? null,
      referenceType: input.referenceType ?? null,
      referenceId: input.referenceId ?? null,
      referenceNo: input.referenceNo ?? null,
      notes: input.notes ?? null,
      metadata: input.metadata ?? Prisma.JsonNull
    }
  });
}
