import { NextResponse } from "next/server";
import { mkdir, readFile, writeFile } from "fs/promises";
import path from "path";
import { backendUrl } from "@/lib/ops-auth";

const DATA_DIR = path.join(process.cwd(), "data");
const FILE = path.join(DATA_DIR, "return-requests.json");

type RequestBody = {
  name?: string;
  email?: string;
  order?: string;
  type?: string;
  message?: string;
};

export async function POST(request: Request) {
  const body = (await request.json().catch(() => null)) as RequestBody | null;
  const name = String(body?.name || "").trim();
  const email = String(body?.email || "")
    .trim()
    .toLowerCase();
  const order = String(body?.order || "").trim();
  const type = String(body?.type || "cambio").trim();
  const message = String(body?.message || "").trim();

  if (!name || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || message.length < 8) {
    return NextResponse.json(
      { message: "Completa nombre, email y un mensaje claro." },
      { status: 400 }
    );
  }

  const entry = {
    name,
    email,
    order,
    type,
    message,
    created_at: new Date().toISOString(),
  };

  await mkdir(DATA_DIR, { recursive: true });
  try {
    const raw = await readFile(FILE, "utf8");
    const list = JSON.parse(raw);
    const next = Array.isArray(list) ? [...list, entry] : [entry];
    await writeFile(FILE, JSON.stringify(next, null, 2));
  } catch {
    await writeFile(FILE, JSON.stringify([entry], null, 2));
  }

  try {
    const res = await fetch(backendUrl("/hooks/ot-contact"), {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(entry),
    });
    if (!res.ok) {
      const data = (await res.json().catch(() => ({}))) as {
        message?: string;
      };
      // Guardado local OK; avisamos si el mail falló
      return NextResponse.json({
        ok: true,
        mailed: false,
        message:
          data.message ||
          "Solicitud guardada. Si no recibes respuesta, escribe a hola@ot.azulado.cloud.",
      });
    }
  } catch {
    return NextResponse.json({
      ok: true,
      mailed: false,
      message:
        "Solicitud guardada. Te responderemos pronto a tu correo.",
    });
  }

  return NextResponse.json({ ok: true, mailed: true });
}
