import { pgTable, serial, text, numeric, integer, timestamp } from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { z } from "zod/v4";

export const supplyOrdersTable = pgTable("supply_orders", {
  id: serial("id").primaryKey(),
  supplierId: integer("supplier_id").notNull(),
  factoryId: integer("factory_id").notNull(),
  date: text("date").notNull(),
  documentNo: text("document_no").notNull(),
  totalAmount: numeric("total_amount", { precision: 15, scale: 2 }).notNull().default("0"),
  notes: text("notes"),
  createdAt: timestamp("created_at").defaultNow().notNull(),
});

export const supplyOrderItemsTable = pgTable("supply_order_items", {
  id: serial("id").primaryKey(),
  orderId: integer("order_id").notNull(),
  productId: integer("product_id").notNull(),
  quantity: numeric("quantity", { precision: 15, scale: 3 }).notNull(),
  unitPrice: numeric("unit_price", { precision: 15, scale: 2 }).notNull(),
  total: numeric("total", { precision: 15, scale: 2 }).notNull(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
});

export const insertSupplyOrderSchema = createInsertSchema(supplyOrdersTable).omit({ id: true, createdAt: true });
export const insertSupplyOrderItemSchema = createInsertSchema(supplyOrderItemsTable).omit({ id: true, createdAt: true });
export type InsertSupplyOrder = z.infer<typeof insertSupplyOrderSchema>;
export type InsertSupplyOrderItem = z.infer<typeof insertSupplyOrderItemSchema>;
export type SupplyOrder = typeof supplyOrdersTable.$inferSelect;
export type SupplyOrderItem = typeof supplyOrderItemsTable.$inferSelect;
