import { sql } from "drizzle-orm";
import { pgTable, text, varchar, integer, timestamp, jsonb } from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { z } from "zod";

export const users = pgTable("users", {
  id: varchar("id").primaryKey().default(sql`gen_random_uuid()`),
  username: text("username").notNull().unique(),
  password: text("password").notNull(),
});

export const leads = pgTable("leads", {
  id: varchar("id").primaryKey().default(sql`gen_random_uuid()`),
  name: text("name").notNull(),
  email: text("email").notNull(),
  phone: text("phone").notNull(),
  company: text("company"),
  zipCode: text("zip_code").notNull(),
  materialTypes: jsonb("material_types").$type<string[]>().notNull(),
  volumeData: jsonb("volume_data").$type<{
    fileBoxes: number;
    filingCabinets: number;
    bags: number;
    pallets: number;
  }>().notNull(),
  totalBoxes: integer("total_boxes").notNull(),
  totalWeight: integer("total_weight").notNull(),
  serviceType: text("service_type").notNull(),
  timeline: text("timeline").notNull(),
  specialRequirements: jsonb("special_requirements").$type<string[]>().notNull().default(sql`'[]'::jsonb`),
  preferredContact: text("preferred_contact").notNull(),
  quoteAmount: integer("quote_amount").notNull(),
  status: text("status").notNull().default("new"),
  source: text("source").notNull().default("widget"),
  createdAt: timestamp("created_at").defaultNow().notNull(),
});

export const insertUserSchema = createInsertSchema(users).pick({
  username: true,
  password: true,
});

export const insertLeadSchema = createInsertSchema(leads).omit({
  id: true,
  createdAt: true,
  status: true,
  source: true,
});

export const leadSubmissionSchema = insertLeadSchema.extend({
  materialTypes: z.array(z.enum(["documents", "hard-drives", "electronics", "mixed"])).min(1),
  serviceType: z.enum(["mobile", "offsite", "dropoff"]),
  timeline: z.enum(["asap", "week", "flexible"]),
  preferredContact: z.enum(["email", "phone", "both"]),
  zipCode: z.string().min(5).max(10),
  name: z.string().min(2),
  email: z.string().email(),
  phone: z.string().min(10),
});

export type InsertUser = z.infer<typeof insertUserSchema>;
export type User = typeof users.$inferSelect;
export type InsertLead = z.infer<typeof insertLeadSchema>;
export type Lead = typeof leads.$inferSelect;
export type LeadSubmission = z.infer<typeof leadSubmissionSchema>;
