import { type User, type InsertUser, type Lead, type InsertLead } from "@shared/schema";
import { randomUUID } from "crypto";

export interface IStorage {
  getUser(id: string): Promise<User | undefined>;
  getUserByUsername(username: string): Promise<User | undefined>;
  createUser(user: InsertUser): Promise<User>;
  createLead(lead: InsertLead): Promise<Lead>;
  getLead(id: string): Promise<Lead | undefined>;
  getLeads(): Promise<Lead[]>;
  updateLeadStatus(id: string, status: string): Promise<Lead | undefined>;
}

export class MemStorage implements IStorage {
  private users: Map<string, User>;
  private leads: Map<string, Lead>;

  constructor() {
    this.users = new Map();
    this.leads = new Map();
  }

  async getUser(id: string): Promise<User | undefined> {
    return this.users.get(id);
  }

  async getUserByUsername(username: string): Promise<User | undefined> {
    return Array.from(this.users.values()).find(
      (user) => user.username === username,
    );
  }

  async createUser(insertUser: InsertUser): Promise<User> {
    const id = randomUUID();
    const user: User = { ...insertUser, id };
    this.users.set(id, user);
    return user;
  }

  async createLead(insertLead: InsertLead): Promise<Lead> {
    const id = randomUUID();
    const lead: Lead = {
      id,
      name: insertLead.name,
      email: insertLead.email,
      phone: insertLead.phone,
      company: insertLead.company || null,
      zipCode: insertLead.zipCode,
      materialTypes: insertLead.materialTypes as string[],
      volumeData: insertLead.volumeData,
      totalBoxes: insertLead.totalBoxes,
      totalWeight: insertLead.totalWeight,
      serviceType: insertLead.serviceType,
      timeline: insertLead.timeline,
      specialRequirements: insertLead.specialRequirements as string[],
      preferredContact: insertLead.preferredContact,
      quoteAmount: insertLead.quoteAmount,
      status: "new",
      source: "widget",
      createdAt: new Date(),
    };
    this.leads.set(id, lead);
    return lead;
  }

  async getLead(id: string): Promise<Lead | undefined> {
    return this.leads.get(id);
  }

  async getLeads(): Promise<Lead[]> {
    return Array.from(this.leads.values());
  }

  async updateLeadStatus(id: string, status: string): Promise<Lead | undefined> {
    const lead = this.leads.get(id);
    if (lead) {
      const updatedLead = { ...lead, status };
      this.leads.set(id, updatedLead);
      return updatedLead;
    }
    return undefined;
  }
}

export const storage = new MemStorage();
