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

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

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

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

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

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

    tags: json("tags").notNull().default([]),

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

    ean: text("ean"),
    barcode: text("barcode"),

    purchase_price: doublePrecision("purchasePrice"),
    selling_price: doublePrecision("sellingPrice"),

    description: text("description"),

    manufacturer_number: text("manufacturerNumber"),

    vendor_allocation: jsonb("vendorAllocation").default([]),

    article_number: text("articleNumber"),
    supplier_link: text("supplierLink"),

    barcodes: text("barcodes").array().notNull().default([]),

    productcategories: jsonb("productcategories").default([]),

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

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

    markup_percentage: doublePrecision("markupPercentage"),

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

export type Product = typeof products.$inferSelect
export type NewProduct = typeof products.$inferInsert
