import { NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/prisma";
import { requireAdmin, unauthorized } from "@/lib/admin-api";

const updateSchema = z
  .object({
    smtpHost: z.string().min(1).optional(),
    smtpPort: z.number().int().positive().optional(),
    smtpUser: z.string().min(1).optional(),
    smtpPass: z.string().min(1).optional(),
    smtpSecure: z.boolean().optional(),
    toEmail: z.string().email().optional(),
    fromEmail: z.string().email().optional(),
    fromName: z.string().min(1).optional(),
  })
  .strict();

export async function GET() {
  const admin = await requireAdmin();
  if (!admin) return unauthorized();

  const cfg = await prisma.smtpConfig.findUnique({ where: { id: "default" } });
  return NextResponse.json({
    smtpHost: cfg?.smtpHost ?? "",
    smtpPort: cfg?.smtpPort ?? null,
    smtpUser: cfg?.smtpUser ?? "",
    smtpSecure: cfg?.smtpSecure ?? false,
    toEmail: cfg?.toEmail ?? "",
    fromEmail: cfg?.fromEmail ?? "",
    fromName: cfg?.fromName ?? "",
    hasPasswordConfigured: Boolean(cfg?.smtpPass),
  });
}

export async function PUT(req: Request) {
  const admin = await requireAdmin();
  if (!admin) return unauthorized();

  const body = updateSchema.parse(await req.json());

  const existing = await prisma.smtpConfig.findUnique({ where: { id: "default" } });

  const data: any = {};
  if (body.smtpHost !== undefined) data.smtpHost = body.smtpHost;
  if (body.smtpPort !== undefined) data.smtpPort = body.smtpPort;
  if (body.smtpUser !== undefined) data.smtpUser = body.smtpUser;
  if (body.smtpSecure !== undefined) data.smtpSecure = body.smtpSecure;
  if (body.toEmail !== undefined) data.toEmail = body.toEmail;
  if (body.fromEmail !== undefined) data.fromEmail = body.fromEmail;
  if (body.fromName !== undefined) data.fromName = body.fromName;

  // Importante: senha só é atualizada se o admin fornecer explicitamente.
  if (body.smtpPass !== undefined) data.smtpPass = body.smtpPass;

  const updated = await prisma.smtpConfig.upsert({
    where: { id: "default" },
    create: {
      id: "default",
      smtpHost: body.smtpHost ?? null,
      smtpPort: body.smtpPort ?? null,
      smtpUser: body.smtpUser ?? null,
      smtpPass: body.smtpPass ?? null,
      smtpSecure: body.smtpSecure ?? false,
      toEmail: body.toEmail ?? null,
      fromEmail: body.fromEmail ?? null,
      fromName: body.fromName ?? null,
    },
    update: {
      smtpHost: data.smtpHost ?? existing?.smtpHost ?? null,
      smtpPort: data.smtpPort ?? existing?.smtpPort ?? null,
      smtpUser: data.smtpUser ?? existing?.smtpUser ?? null,
      smtpSecure: data.smtpSecure ?? existing?.smtpSecure ?? false,
      toEmail: data.toEmail ?? existing?.toEmail ?? null,
      fromEmail: data.fromEmail ?? existing?.fromEmail ?? null,
      fromName: data.fromName ?? existing?.fromName ?? null,
      smtpPass: data.smtpPass ?? existing?.smtpPass ?? null,
    },
  });

  return NextResponse.json({
    ok: true,
    hasPasswordConfigured: Boolean(updated.smtpPass),
  });
}

