import { NextRequest, NextResponse } from "next/server";
import { getThemeId, isValidTheme } from "@/types/theme";
import { readFileSync, writeFileSync, existsSync } from "fs";
import { join } from "path";
import type { SiteInfo } from "@/types/data";

const DATA_DIR = join(process.cwd(), 'data');
const SITEINFO_FILE = join(DATA_DIR, 'siteinfo.json');

/**
 * API route for setting the site theme
 * Used by admin panel to set site-wide default theme
 * Updates siteinfo.json with the default theme (affects all users)
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { theme } = body;

    if (!isValidTheme(theme)) {
      return NextResponse.json(
        { error: "Invalid theme ID" },
        { status: 400 }
      );
    }

    // Update siteinfo.json with the default theme (site-wide setting)
    let siteInfo: SiteInfo;
    if (existsSync(SITEINFO_FILE)) {
      const fileContent = readFileSync(SITEINFO_FILE, 'utf-8');
      siteInfo = JSON.parse(fileContent);
    } else {
      return NextResponse.json(
        { error: "Siteinfo file not found" },
        { status: 404 }
      );
    }
    
    // Update default theme in siteinfo
    siteInfo = { ...siteInfo, defaultTheme: theme };
    writeFileSync(SITEINFO_FILE, JSON.stringify(siteInfo, null, 2));

    return NextResponse.json(
      { success: true, theme },
      {
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  } catch (error) {
    console.error("Error setting theme:", error);
    return NextResponse.json(
      { error: "Failed to set theme" },
      { 
        status: 500,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }
}

/**
 * GET endpoint to retrieve current site-wide default theme
 */
export async function GET() {
  try {
    // Read site-wide default theme from siteinfo.json
    if (!existsSync(SITEINFO_FILE)) {
      return NextResponse.json({ theme: "2" }, {
        headers: {
          'Cache-Control': 'public, s-maxage=300, stale-while-revalidate=600',
        },
      }); // Default fallback
    }
    
    const fileContent = readFileSync(SITEINFO_FILE, 'utf-8');
    const siteInfo = JSON.parse(fileContent) as SiteInfo;
    const theme = getThemeId(siteInfo.defaultTheme || "2");
    
    return NextResponse.json({ theme }, {
      headers: {
        'Cache-Control': 'public, s-maxage=300, stale-while-revalidate=600',
      },
    });
  } catch (error) {
    console.error("Error getting theme:", error);
    return NextResponse.json(
      { error: "Failed to get theme" },
      { 
        status: 500,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }
}

