import { getSessionUser } from "@/lib/auth";
import {
  deleteMailboxContactsByEmail,
  getMailboxContactSettingsByEmail,
  getMailboxSenderProfileByEmail,
  saveMailboxContactByEmail
} from "@/lib/official-mail";

function contactError(error: unknown) {
  const code = error instanceof Error ? error.message : "contact-failed";
  const message =
    code === "contact-invalid-email"
      ? "올바른 이메일 주소를 입력해주세요."
      : code === "contact-email-exists"
        ? "이미 주소록에 등록된 이메일입니다."
        : code === "contact-not-found"
          ? "주소록 항목을 찾지 못했습니다."
          : code === "contact-auto-folder-invalid" || code === "folder-not-found"
            ? "자동분류할 내 메일함을 다시 선택해주세요."
            : "주소록을 처리하지 못했습니다. 잠시 후 다시 시도해주세요.";
  return Response.json({ error: code, message, ok: false }, { status: code === "contact-not-found" ? 404 : 400 });
}

export async function GET(request: Request) {
  const user = await getSessionUser();
  if (!user) return Response.json({ error: "unauthorized", ok: false }, { status: 401 });

  try {
    const sender = new URL(request.url).searchParams.get("sender")?.trim();
    if (sender) {
      return Response.json({ ok: true, profile: await getMailboxSenderProfileByEmail(user.email, sender) });
    }
    return Response.json({ ok: true, settings: await getMailboxContactSettingsByEmail(user.email) });
  } catch (error) {
    return contactError(error);
  }
}

export async function POST(request: Request) {
  const user = await getSessionUser();
  if (!user) return Response.json({ error: "unauthorized", ok: false }, { status: 401 });
  const payload = (await request.json().catch(() => null)) as Record<string, unknown> | null;

  try {
    const contact = await saveMailboxContactByEmail(user.email, {
      autoMoveFolder: typeof payload?.autoMoveFolder === "string" ? payload.autoMoveFolder : null,
      companyName: String(payload?.companyName ?? ""),
      contactId: Number(payload?.contactId ?? 0) || null,
      displayName: String(payload?.displayName ?? ""),
      email: String(payload?.email ?? ""),
      groupName: String(payload?.groupName ?? ""),
      isVip: Boolean(payload?.isVip),
      memo: String(payload?.memo ?? ""),
      moveExistingMessages: Boolean(payload?.moveExistingMessages),
      phone: String(payload?.phone ?? "")
    });
    return Response.json({ contact, ok: true });
  } catch (error) {
    return contactError(error);
  }
}

export async function DELETE(request: Request) {
  const user = await getSessionUser();
  if (!user) return Response.json({ error: "unauthorized", ok: false }, { status: 401 });
  const payload = (await request.json().catch(() => null)) as { contactIds?: Array<number | string> } | null;

  try {
    const deletedCount = await deleteMailboxContactsByEmail(user.email, payload?.contactIds ?? []);
    return Response.json({ deletedCount, ok: true });
  } catch (error) {
    return contactError(error);
  }
}
