import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import {
  requireApiAuth,
  requireApiAuthWithPermission,
  handleApiError,
} from "@/lib/api-auth";

export async function GET() {
  try {
    await requireApiAuth();
    const settings = await prisma.appSettings.findUnique({
      where: { id: "singleton" },
    });

    if (!settings) {
      const created = await prisma.appSettings.create({
        data: { id: "singleton" },
      });
      return NextResponse.json(created);
    }

    const masked = { ...settings } as Record<string, unknown>;
    if (masked.mondayApiToken) masked.mondayApiToken = "••••" + (masked.mondayApiToken as string).slice(-4);
    if (masked.webhookSecret) masked.webhookSecret = "••••" + (masked.webhookSecret as string).slice(-4);
    if (masked.emailImapPass) masked.emailImapPass = "••••••••";
    if (masked.ftpPass) masked.ftpPass = "••••••••";
    return NextResponse.json(masked);
  } catch (error) {
    return handleApiError(error);
  }
}

export async function PUT(request: NextRequest) {
  try {
    await requireApiAuthWithPermission("settings.edit");
    const body = await request.json().catch(() => ({}));
    const data: Record<string, unknown> = {};

    if (body.ollamaUrl != null) data.ollamaUrl = String(body.ollamaUrl);
    if (body.model != null) data.model = String(body.model);
    if (body.watchDir != null) data.watchDir = String(body.watchDir);
    if (body.watching != null) data.watching = Boolean(body.watching);
    if (body.sourceRetentionDays != null) data.sourceRetentionDays = Math.max(1, parseInt(String(body.sourceRetentionDays)) || 30);
    if (body.imageRetentionDays != null) data.imageRetentionDays = Math.max(1, parseInt(String(body.imageRetentionDays)) || 180);
    if (body.aiProvider != null) data.aiProvider = String(body.aiProvider);
    if (body.aiModel != null) data.aiModel = String(body.aiModel);

    if (body.mondayApiToken != null) data.mondayApiToken = String(body.mondayApiToken);
    if (body.mondayBoardId != null) data.mondayBoardId = String(body.mondayBoardId);
    if (body.mondayEnabled != null) data.mondayEnabled = Boolean(body.mondayEnabled);
    if (body.mondayColumnMap !== undefined) data.mondayColumnMap = body.mondayColumnMap;
    if (body.mondayWebhookUrl != null) data.mondayWebhookUrl = String(body.mondayWebhookUrl);

    if (body.webhookUrl != null) data.webhookUrl = String(body.webhookUrl);
    if (body.webhookSecret != null) data.webhookSecret = String(body.webhookSecret);
    if (body.webhookEnabled != null) data.webhookEnabled = Boolean(body.webhookEnabled);
    if (body.webhookEvents !== undefined) data.webhookEvents = body.webhookEvents;

    if (body.emailImapHost != null) data.emailImapHost = String(body.emailImapHost);
    if (body.emailImapPort != null) data.emailImapPort = Math.max(1, parseInt(String(body.emailImapPort)) || 993);
    if (body.emailImapUser != null) data.emailImapUser = String(body.emailImapUser);
    if (body.emailImapPass != null) data.emailImapPass = String(body.emailImapPass);
    if (body.emailImapTls != null) data.emailImapTls = Boolean(body.emailImapTls);
    if (body.emailFolder != null) data.emailFolder = String(body.emailFolder);
    if (body.emailProcessed != null) data.emailProcessed = String(body.emailProcessed);
    if (body.emailProcessedFolder != null) data.emailProcessedFolder = String(body.emailProcessedFolder);

    if (body.ftpEnabled != null) data.ftpEnabled = Boolean(body.ftpEnabled);
    if (body.ftpHost != null) data.ftpHost = String(body.ftpHost);
    if (body.ftpPort != null) data.ftpPort = Math.max(1, parseInt(String(body.ftpPort)) || 21);
    if (body.ftpUser != null) data.ftpUser = String(body.ftpUser);
    if (body.ftpPass != null) data.ftpPass = String(body.ftpPass);
    if (body.ftpProtocol != null && ["sftp", "ftp", "ftps"].includes(body.ftpProtocol))
      data.ftpProtocol = String(body.ftpProtocol);
    if (body.ftpIncomingDir != null) data.ftpIncomingDir = String(body.ftpIncomingDir);
    if (body.ftpProcessedDir != null) data.ftpProcessedDir = String(body.ftpProcessedDir);

    const settings = await prisma.appSettings.upsert({
      where: { id: "singleton" },
      create: {
        id: "singleton",
        ollamaUrl: (data.ollamaUrl as string) ?? "http://192.168.68.108:11434",
        model: (data.model as string) ?? "llava:7b",
        watchDir: (data.watchDir as string) ?? "",
        watching: (data.watching as boolean) ?? false,
      },
      update: data as Parameters<typeof prisma.appSettings.update>[0]["data"],
    });

    return NextResponse.json(settings);
  } catch (error) {
    return handleApiError(error);
  }
}
