import {
  getConfigFromRedis,
  setConfigToRedis,
} from "@/apifetchers/mutual/context/page/config/fetch";
import { AuthError } from "@/types/mutual/context/validations";
import { NextResponse } from "next/server";

export async function GET() {
  try {
    const config = await getConfigFromRedis();
    return NextResponse.json(config);
  } catch (error) {
    if (error instanceof AuthError) {
      // Return 401 Unauthorized for authentication errors
      return new NextResponse(JSON.stringify({ error: error.message }), {
        status: 401,
        headers: { "Content-Type": "application/json" },
      });
    }
    // For other errors, return 500 Internal Server Error
    return new NextResponse(
      JSON.stringify({ error: "Internal server error" }),
      {
        status: 500,
        headers: { "Content-Type": "application/json" },
      }
    );
  }
}

export async function POST(request: Request) {
  try {
    const config = await request.json();
    await setConfigToRedis(config);
    return NextResponse.json(config);
  } catch (error) {
    if (error instanceof AuthError) {
      return new NextResponse(JSON.stringify({ error: error.message }), {
        status: 401,
        headers: { "Content-Type": "application/json" },
      });
    }
    return new NextResponse(
      JSON.stringify({ error: "Internal server error" }),
      {
        status: 500,
        headers: { "Content-Type": "application/json" },
      }
    );
  }
}
