import {
  pgTable,
  uuid,
  text,
  timestamp,
  index,
} from "drizzle-orm/pg-core";
import { brigades } from "./brigades";
import { vehicleTemplates } from "./templates";
import { equipmentCategories } from "./equipment-categories";
import { assetStatusEnum } from "./enums";

/**
 * Fahrzeuge. `templateId` -> set null (Eigenbau). `funkrufname` ist SPALTE
 * (kein Merkmal). `status` über asset_status-Enum.
 */
export const vehicles = pgTable(
  "vehicles",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    brigadeId: uuid("brigade_id")
      .notNull()
      .references(() => brigades.id, { onDelete: "cascade" }),
    templateId: uuid("template_id").references(() => vehicleTemplates.id, {
      onDelete: "set null",
    }),
    name: text("name").notNull(),
    funkrufname: text("funkrufname"),
    status: assetStatusEnum("status").notNull().default("einsatzbereit"),
    notiz: text("notiz"),
    erstelltAm: timestamp("erstellt_am", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => ({
    brigadeIdx: index("vehicles_brigade_idx").on(t.brigadeId),
    templateIdx: index("vehicles_template_idx").on(t.templateId),
  }),
);

/**
 * Geräte/Beladung. `vehicleId = NULL` => im Gerätehaus.
 */
export const equipment = pgTable(
  "equipment",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    brigadeId: uuid("brigade_id")
      .notNull()
      .references(() => brigades.id, { onDelete: "cascade" }),
    categoryId: uuid("category_id")
      .notNull()
      .references(() => equipmentCategories.id, { onDelete: "restrict" }),
    vehicleId: uuid("vehicle_id").references(() => vehicles.id, {
      onDelete: "set null",
    }),
    name: text("name").notNull(),
    status: assetStatusEnum("status").notNull().default("einsatzbereit"),
    erstelltAm: timestamp("erstellt_am", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => ({
    brigadeIdx: index("equipment_brigade_idx").on(t.brigadeId),
    categoryIdx: index("equipment_category_idx").on(t.categoryId),
    vehicleIdx: index("equipment_vehicle_idx").on(t.vehicleId),
  }),
);
