import {
    pgTable,
    bigint,
    timestamp,
    text,
    doublePrecision,
    jsonb,
    boolean,
    smallint,
    uuid,
} from "drizzle-orm/pg-core"

import { tenants } from "./tenants"
import { units } from "./units"
import { authUsers } from "./auth_users"
import { costcentres } from "./costcentres"

export const services = pgTable("services", {
    id: bigint("id", { mode: "number" })
        .primaryKey()
        .generatedByDefaultAsIdentity(),

    createdAt: timestamp("created_at", { withTimezone: true })
        .notNull()
        .defaultNow(),

    name: text("name").notNull(),

    sellingPrice: doublePrecision("sellingPrice"),

    description: text("description"),

    tenant: bigint("tenant", { mode: "number" })
        .notNull()
        .references(() => tenants.id),

    unit: bigint("unit", { mode: "number" }).references(() => units.id),

    costcentre: uuid("costcentre").references(() => costcentres.id),

    serviceNumber: bigint("serviceNumber", { mode: "number" }),

    tags: jsonb("tags").default([]),
    servicecategories: jsonb("servicecategories").notNull().default([]),

    archived: boolean("archived").notNull().default(false),

    purchasePriceComposed: jsonb("purchasePriceComposed")
        .notNull()
        .default({ total: 0 }),

    sellingPriceComposed: jsonb("sellingPriceComposed")
        .notNull()
        .default({ total: 0 }),

    taxPercentage: smallint("taxPercentage").notNull().default(19),

    materialComposition: jsonb("materialComposition").notNull().default([]),
    personalComposition: jsonb("personalComposition").notNull().default([]),
    priceUpdateLocked: boolean("priceUpdateLocked").notNull().default(false),

    updatedAt: timestamp("updated_at", { withTimezone: true }),
    updatedBy: uuid("updated_by").references(() => authUsers.id),
})

export type Service = typeof services.$inferSelect
export type NewService = typeof services.$inferInsert
