import {
  getMenuFromRedis,
  setMenuToRedis,
} from "@/apifetchers/mutual/context/page/menu/fetch";
import { AuthError } from "@/types/mutual/context/validations";
import { NextResponse } from "next/server";

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

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