import { customType, timestamp, uuid } from 'drizzle-orm/pg-core';
import Decimal from 'decimal.js';
import { sql } from 'drizzle-orm';

/**
 * Column helpers shared by all schema files.
 *
 * Decimal columns are mapped to decimal.js instances so services never do
 * floating point arithmetic on quantities or money.
 */

function decimalType(name: string, precision: number, scale: number) {
  return customType<{ data: Decimal; driverData: string; config: undefined }>({
    dataType() {
      return `numeric(${precision}, ${scale})`;
    },
    fromDriver(value: string) {
      return new Decimal(value);
    },
    toDriver(value: Decimal | number | string) {
      return new Decimal(value).toFixed(scale);
    },
  })(name);
}

/** Quantity in base UoM: numeric(18,4) */
export const qty = (name: string) => decimalType(name, 18, 4);
/** Money: numeric(18,4) (KWD uses 3 dp, most currencies 2; 4 keeps rounding headroom) */
export const money = (name: string) => decimalType(name, 18, 4);
/** Rate: numeric(18,6) */
export const rate = (name: string) => decimalType(name, 18, 6);
/** Volume in m3: numeric(18,6) */
export const cbm = (name: string) => decimalType(name, 18, 6);
/** Weight in kg: numeric(18,4) */
export const kg = (name: string) => decimalType(name, 18, 4);
/** Dimension in cm: numeric(10,2) */
export const cm = (name: string) => decimalType(name, 10, 2);
/** Percentage: numeric(6,3) */
export const pct = (name: string) => decimalType(name, 6, 3);
/** Temperature: numeric(6,2) */
export const temperature = (name: string) => decimalType(name, 6, 2);

export const id = () => uuid('id').primaryKey().defaultRandom();
export const tenantId = () => uuid('tenant_id').notNull();
export const createdAt = () => timestamp('created_at', { withTimezone: true }).notNull().defaultNow();
export const updatedAt = () =>
  timestamp('updated_at', { withTimezone: true })
    .notNull()
    .defaultNow()
    .$onUpdate(() => new Date());
export const ts = (name: string) => timestamp(name, { withTimezone: true });

export const ZERO = new Decimal(0);
export const now = sql`now()`;
