import { pgTable, text, serial, timestamp, integer, varchar, check } from "drizzle-orm/pg-core";
import { sql } from "drizzle-orm";
import { createInsertSchema } from "drizzle-zod";
import { z } from "zod/v4";
import { usersTable } from "./users";
import { servicesTable } from "./services";

export const serviceOrdersTable = pgTable(
  "service_orders",
  {
    id: serial("id").primaryKey(),
    userId: integer("user_id").notNull().references(() => usersTable.id, { onDelete: "cascade" }),
    serviceId: integer("service_id").notNull().references(() => servicesTable.id, { onDelete: "restrict" }),
    notes: text("notes"),
    status: varchar("status", { length: 20 }).notNull().default("pending"),
    assignedTo: integer("assigned_to").references(() => usersTable.id, { onDelete: "set null" }),
    createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => new Date()),
  },
  (t) => [
    check(
      "service_orders_status_check",
      sql`${t.status} IN ('pending','received','preparing','completed','cancelled')`,
    ),
  ],
);

export const insertServiceOrderSchema = createInsertSchema(serviceOrdersTable).omit({
  id: true,
  createdAt: true,
  updatedAt: true,
  status: true,
  assignedTo: true,
});
export type InsertServiceOrder = z.infer<typeof insertServiceOrderSchema>;
export type ServiceOrder = typeof serviceOrdersTable.$inferSelect;

export const SERVICE_ORDER_STATUSES = [
  "pending",
  "received",
  "preparing",
  "completed",
  "cancelled",
] as const;
export type ServiceOrderStatus = (typeof SERVICE_ORDER_STATUSES)[number];
