import { NextRequest, NextResponse } from "next/server";
import { setLanguage } from "@/lib/language";
import { getLanguageCode, isValidLanguage } from "@/types/language";
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 language
 * Used by admin panel to set site-wide default language
 * Updates siteinfo.json with the default language (affects all users)
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { language } = body;

    if (!isValidLanguage(language)) {
      return NextResponse.json(
        { error: "Invalid language code" },
        { status: 400 }
      );
    }

    // Update siteinfo.json with the default language (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 language in siteinfo
    siteInfo = { ...siteInfo, defaultLanguage: language };
    writeFileSync(SITEINFO_FILE, JSON.stringify(siteInfo, null, 2));

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

/**
 * GET endpoint to retrieve current site-wide default language
 */
export async function GET() {
  try {
    // Read site-wide default language from siteinfo.json
    if (!existsSync(SITEINFO_FILE)) {
      return NextResponse.json({ language: "pt" }, {
        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 language = getLanguageCode(siteInfo.defaultLanguage || "pt");
    
    return NextResponse.json({ language }, {
      headers: {
        'Cache-Control': 'public, s-maxage=300, stale-while-revalidate=600',
      },
    });
  } catch (error) {
    console.error("Error getting language:", error);
    return NextResponse.json(
      { error: "Failed to get language" },
      { 
        status: 500,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }
}

