import { NextResponse } from "next/server";
import { getCollection } from "@/lib/mongodb";

// GET - Fetch all vendors
export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const countOnly = searchParams.get("count") === "true";

    const vendorsCollection = await getCollection<any>("vendors");

    if (countOnly) {
      const total = await vendorsCollection.countDocuments({});
      return NextResponse.json({ count: total });
    }

    const vendors = await vendorsCollection.find({}).sort({ createdAt: -1 }).toArray();

    return NextResponse.json({
      vendors: vendors.map((vendor: any) => ({
        ...vendor,
        _id: vendor._id.toString(),
      })),
    });
  } catch (error) {
    console.error("Error fetching vendors:", error);
    return NextResponse.json(
      {
        error: "Failed to fetch vendors",
        details: error instanceof Error ? error.message : "Unknown error",
      },
      { status: 500 }
    );
  }
}

// POST - Create a new vendor
export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { name, email, phone, address, status, companyName, taxId, notes } = body;

    // Validate required fields
    if (!name || !email || !phone || !address) {
      return NextResponse.json(
        { error: "Name, email, phone, and address are required" },
        { status: 400 }
      );
    }

    const vendorsCollection = await getCollection<any>("vendors");

    // Check if vendor already exists
    const existingVendor = await vendorsCollection.findOne({ email });
    if (existingVendor) {
      return NextResponse.json(
        { error: "Vendor with this email already exists" },
        { status: 400 }
      );
    }

    // Create vendor
    const vendorData = {
      name,
      email,
      phone,
      address,
      status: status || "active",
      companyName: companyName || "",
      taxId: taxId || "",
      notes: notes || "",
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };

    const result = await vendorsCollection.insertOne(vendorData);

    if (!result.acknowledged) {
      throw new Error("Failed to create vendor");
    }

    return NextResponse.json(
      {
        success: true,
        message: "Vendor created successfully",
        vendor: {
          ...vendorData,
          _id: result.insertedId.toString(),
        },
      },
      { status: 201 }
    );
  } catch (error) {
    console.error("Error creating vendor:", error);
    return NextResponse.json(
      {
        error: "Failed to create vendor",
        details: error instanceof Error ? error.message : "Unknown error",
      },
      { status: 500 }
    );
  }
}

