import { getSessionUser } from "@/lib/auth";
import {
  getMailSignatureByEmail,
  updateMailSignatureByEmail,
} from "@/lib/mail-signature";

export const runtime = "nodejs";

export async function GET() {
  const user = await getSessionUser();

  if (!user) {
    return Response.json({ error: "unauthorized" }, { status: 401 });
  }

  try {
    return Response.json({ ok: true, signature: await getMailSignatureByEmail(user.email) });
  } catch (error) {
    console.error("Mail signature load failed", error);
    return Response.json({ error: "서명을 불러오지 못했습니다." }, { status: 500 });
  }
}

export async function PUT(request: Request) {
  const user = await getSessionUser();

  if (!user) {
    return Response.json({ error: "unauthorized" }, { status: 401 });
  }

  try {
    const body = (await request.json()) as {
      enabled?: unknown;
      html?: unknown;
      imageWidth?: unknown;
    };
    const signature = await updateMailSignatureByEmail({
      email: user.email,
      enabled: body.enabled === true,
      html: body.html,
      imageWidth: body.imageWidth,
    });

    return Response.json({ ok: true, signature });
  } catch (error) {
    if (error instanceof Error && error.message === "signature-empty") {
      return Response.json({ error: "사용할 서명 내용이나 이미지를 추가해주세요." }, { status: 400 });
    }

    if (error instanceof Error && error.message === "signature-too-long") {
      return Response.json({ error: "서명 내용이 너무 깁니다." }, { status: 400 });
    }

    console.error("Mail signature update failed", error);
    return Response.json({ error: "서명을 저장하지 못했습니다." }, { status: 500 });
  }
}
