import {
  getSelectionFromRedis,
  setSelectionToRedis,
} from "@/apifetchers/mutual/context/dash/selection/fetch";
import { AuthError } from "@/types/mutual/context/validations";
import { NextResponse } from "next/server";

export async function GET() {
  try {
    const selection = await getSelectionFromRedis();
    return NextResponse.json({
      status: 200,
      data: selection || null,
    });
  } 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 selection = await request.json();
    await setSelectionToRedis(selection);
    return NextResponse.json({
      status: 200,
      data: selection || null,
    });
  } 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" },
      }
    );
  }
}
