import { NextResponse } from "next/server";
import { PrismaClient } from "@prisma/client";
import { loadSystemConfig, saveSystemConfig } from "@/lib/system-config";
import { cookies } from "next/headers";
import { verifySession } from "@/lib/auth/jwt";
import { getCached, setCached, deleteCached, cacheKeys } from "@/lib/redis";

export const runtime = "nodejs";

const prisma = new PrismaClient();

async function validateSession() {
  const cookieStore = await cookies();
  const token = cookieStore.get("ep_session")?.value;
  if (!token) return null;
  try {
    const decoded = await verifySession(token);
    return decoded;
  } catch {
    return null;
  }
}

export async function GET() {
  try {
    const session = await validateSession();
    if (!session || session.role !== "ADMIN") {
      return NextResponse.json(
        { ok: false, message: "Unauthorized" },
        { status: 401 }
      );
    }

    // Try to get from cache first
    let cachedSetup = await getCached(cacheKeys.adminSetup);
    if (cachedSetup) {
      return NextResponse.json({
        ok: true,
        data: cachedSetup,
      });
    }

    const appSetup = await prisma.appSetup.findUnique({
      where: { id: 1 },
    });

    const systemConfig = await loadSystemConfig();

    const setupData = {
      googleAuth: {
        enabled: appSetup?.googleAuthEnabled || false,
        clientId: systemConfig.googleAuth?.clientId || "",
        clientSecret: systemConfig.googleAuth?.clientSecret || "",
      },
      oauth: {
        google: { enabled: false, clientId: "", clientSecret: "" },
        github: { enabled: false, clientId: "", clientSecret: "" },
        facebook: { enabled: false, clientId: "", clientSecret: "" },
        discord: { enabled: false, clientId: "", clientSecret: "" },
      },
      googleCalendar: {
        enabled: systemConfig.googleCalendar?.enabled || false,
        serviceAccountEmail: systemConfig.googleCalendar?.serviceAccountEmail || "",
        serviceAccountKey: systemConfig.googleCalendar?.serviceAccountKey || "",
        calendarId: systemConfig.googleCalendar?.calendarId || "",
      },
      socials: appSetup?.socials || {},
      email: {
        smtp: {
          enabled: systemConfig.email?.enabled || false,
          host: systemConfig.email?.smtp?.host || "",
          port: systemConfig.email?.smtp?.port || 587,
          username: systemConfig.email?.smtp?.user || "",
          password: systemConfig.email?.smtp?.pass || "",
          from: systemConfig.email?.from || "",
        },
      },
      pagination: {
        itemsPerPage: appSetup?.paginationItemsPerPage || 10,
      },
    };

    // Cache for 5 minutes
    await setCached(cacheKeys.adminSetup, setupData, 300);

    return NextResponse.json({
      ok: true,
      data: setupData,
    });
  } catch (error) {
    console.error("Error fetching admin setup:", error);
    return NextResponse.json(
      { ok: false, message: "Failed to fetch configuration" },
      { status: 500 }
    );
  }
}

export async function POST(request: Request) {
  try {
    const session = await validateSession();
    if (!session || session.role !== "ADMIN") {
      return NextResponse.json(
        { ok: false, message: "Unauthorized" },
        { status: 401 }
      );
    }

    const body = await request.json();
    const { googleAuth, googleCalendar, socials, email, pagination } = body;

    // Update database for public-facing settings
    await prisma.appSetup.upsert({
      where: { id: 1 },
      update: {
        googleAuthEnabled: googleAuth?.enabled || false,
        socials: socials || {},
        paginationItemsPerPage: pagination?.itemsPerPage || 10,
      },
      create: {
        id: 1,
        googleAuthEnabled: googleAuth?.enabled || false,
        socials: socials || {},
        paginationItemsPerPage: pagination?.itemsPerPage || 10,
        categories: ["Basics", "Planning", "Tax", "Healthcare", "Advanced"],
      },
    });

    // Update system-config.json for sensitive data
    const currentConfig = await loadSystemConfig();
    const updatedConfig = {
      ...currentConfig,
      googleAuth: {
        clientId: googleAuth?.clientId || "",
        clientSecret: googleAuth?.clientSecret || "",
        redirectUri: `${process.env.APP_BASE_URL || "http://localhost:3001"}/auth/google/callback`,
      },
      googleCalendar: {
        enabled: googleCalendar?.enabled || false,
        serviceAccountEmail: googleCalendar?.serviceAccountEmail || "",
        serviceAccountKey: googleCalendar?.serviceAccountKey || "",
        calendarId: googleCalendar?.calendarId || "",
      },
      email: {
        ...currentConfig.email,
        smtp: {
          enabled: email?.smtp?.enabled || false,
          host: email?.smtp?.host || "",
          port: email?.smtp?.port || 587,
          user: email?.smtp?.username || "",
          pass: email?.smtp?.password || "",
        },
        from: email?.smtp?.from || "",
      },
    };

    await saveSystemConfig(updatedConfig, prisma);
    
    // Invalidate cache after update
    await deleteCached(cacheKeys.adminSetup);
    
    console.log("[SETUP] Configuration saved");

    return NextResponse.json({
      ok: true,
      message: "Configuration updated successfully",
    });
  } catch (error) {
    console.error("Error updating admin setup:", error);
    return NextResponse.json(
      { ok: false, message: "Failed to update configuration" },
      { status: 500 }
    );
  }
}
