import { NextRequest, NextResponse } from "next/server";
import dbConnect from "../../lib/mongodb";
import Appointment from "../../models/appointment";
import Store from "@/models/Store";
import { sendTemplateMail } from "@/lib/email";
import GeneralSettings from "@/models/GeneralSettings";

export async function GET() {
  try {
    await dbConnect();

    const stores = await Store.find({ isActive: true }).sort({ createdAt: -1 });

    return NextResponse.json({
      success: true,
      data: stores,
    });
  } catch (err: any) {
    console.error("Store GET error", err);

    return NextResponse.json(
      {
        success: false,
        error: err.message || "Failed to fetch stores",
      },
      { status: 500 },
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    await dbConnect();
    const body = await request.json();
    const {
      storeId,
      storeName,
      date,
      timeSlot,
      slotPeriod,
      name,
      phone,
      email,
      celebrating,
      celebratingOther,
      lookingFor,
    } = body;
    if (
      !storeId ||
      !storeName ||
      !date ||
      !timeSlot ||
      !slotPeriod ||
      !name ||
      !phone ||
      !email ||
      !celebrating
    ) {
      return NextResponse.json(
        { success: false, error: "Missing required fields" },
        { status: 400 },
      );
    }
    const admindetails = await GeneralSettings.findOne();
    try {
      await sendTemplateMail({
        slug: "appointment",
        to: email,
        replyTo: email,
        templateData: { name, email, phone },
      });
      await sendTemplateMail({
        slug: "admin-appointment",
        to: admindetails.email,
        replyTo: admindetails.email,
        templateData: { name, email, phone },
      });
    } catch (err: any) {
      console.error("Contact notification email failed", err);
    }

    const appointment = new Appointment({
      storeId,
      storeName,
      date,
      timeSlot,
      slotPeriod,
      name,
      phone,
      email,
      celebrating,
      celebratingOther,
      lookingFor,
    });

    await appointment.save();
    return NextResponse.json({ success: true, data: appointment });
  } catch (err: any) {
    console.error("Appointment POST error", err);
    return NextResponse.json(
      { success: false, error: err.message || "Failed to create appointment" },
      { status: 500 },
    );
  }
}
