import { QuoteRequest } from "../models/QuoteRequest.js";
import mongoose from "mongoose";

const memoryQuotes = [];

function hasDatabase() {
  return mongoose.connection.readyState === 1;
}

export async function createQuoteRequest(request, response) {
  if (!hasDatabase()) {
    const quote = {
      ...request.body,
      _id: `local-${Date.now()}`,
      status: "New",
      quotedAmount: request.body.quotedAmount || 0,
      invoiceNumber: request.body.invoiceNumber || "",
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
    memoryQuotes.unshift(quote);
    return response.status(201).json(quote);
  }
  const quote = await QuoteRequest.create(request.body);
  request.app.get("io")?.emit("quote:created", quote);
  response.status(201).json(quote);
}

export async function listQuoteRequests(_request, response) {
  if (!hasDatabase()) return response.json(memoryQuotes);
  const quotes = await QuoteRequest.find().sort("-createdAt").limit(250);
  response.json(quotes);
}

export async function updateQuoteRequest(request, response) {
  const update = { ...request.body };
  if (update.quotedAmount && !update.invoiceNumber) {
    update.invoiceNumber = `OMQ-INV-${Date.now()}`;
  }
  if (!hasDatabase()) {
    const index = memoryQuotes.findIndex((quote) => quote._id === request.params.id);
    if (index === -1) return response.status(404).json({ message: "Quote not found" });
    memoryQuotes[index] = { ...memoryQuotes[index], ...update, updatedAt: new Date().toISOString() };
    return response.json(memoryQuotes[index]);
  }
  const quote = await QuoteRequest.findByIdAndUpdate(request.params.id, update, { new: true });
  response.json(quote);
}
