import {
  getOnlineFromRedis,
  setOnlineToRedis,
} from "@/apifetchers/mutual/context/page/online/fetch";
import { AuthError } from "@/types/mutual/context/validations";
import { NextResponse } from "next/server";

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