/**
 * Orders + order_items. Source: `db/migrations/0001_init.sql`.
 */
import {
  pgTable,
  uuid,
  text,
  integer,
  timestamp,
  index,
} from "drizzle-orm/pg-core";
import { brands } from "./brands";
import { customers } from "./customers";
import { stops } from "./stops";
import { products } from "./products";

export const orders = pgTable(
  "orders",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    brandId: uuid("brand_id")
      .notNull()
      .references(() => brands.id, { onDelete: "cascade" }),
    customerId: uuid("customer_id").references(() => customers.id, {
      onDelete: "set null",
    }),
    stopId: uuid("stop_id").references(() => stops.id, {
      onDelete: "set null",
    }),
    totalCents: integer("total_cents").notNull().default(0),
    status: text("status", {
      enum: ["pending", "confirmed", "fulfilled", "canceled"],
    }).notNull().default("pending"),
    fulfillment: text("fulfillment", {
      enum: ["pickup", "ship", "mixed"],
    }).notNull(),
    customerAddress: text("customer_address"),
    customerCity: text("customer_city"),
    customerState: text("customer_state"),
    customerZip: text("customer_zip"),
    idempotencyKey: text("idempotency_key"),
    notes: text("notes"),
    placedAt: timestamp("placed_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
    updatedAt: timestamp("updated_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => ({
    brandIdx: index("orders_brand_idx").on(t.brandId),
    statusIdx: index("orders_status_idx").on(t.brandId, t.status),
    stopIdx: index("orders_stop_idx").on(t.stopId),
    customerIdx: index("orders_customer_idx").on(t.customerId),
  }),
);

export const orderItems = pgTable(
  "order_items",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    orderId: uuid("order_id")
      .notNull()
      .references(() => orders.id, { onDelete: "cascade" }),
    productId: uuid("product_id").references(() => products.id, {
      onDelete: "set null",
    }),
    quantity: integer("quantity").notNull(),
    priceCents: integer("price_cents").notNull(),
    fulfillment: text("fulfillment", {
      enum: ["pickup", "ship"],
    }).notNull(),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => ({
    orderIdx: index("order_items_order_idx").on(t.orderId),
  }),
);

export type Order = typeof orders.$inferSelect;
export type NewOrder = typeof orders.$inferInsert;
export type OrderItem = typeof orderItems.$inferSelect;
export type NewOrderItem = typeof orderItems.$inferInsert;
