import {
  deleteMedia,
  getGallery,
  updateGalleryById,
} from "@/models/gallery.model";
import { response } from "@/utils/helper";

export async function GET(request) {
  try {
    const { searchParams } = new URL(request.url);
    const searchParamsData = Object.fromEntries(searchParams.entries());
    const queryRole = {
      page: parseInt(searchParamsData?.page) || 1,
      limit: parseInt(searchParamsData?.limit) || 100,
      sortBy: searchParamsData?.sortBy || "createdAt",
      with: searchParamsData?.with || "desc",
      search: searchParamsData?.search || null,
    };
    const sortRole = {
      asc: 1,
      desc: -1,
    };

    const galleries = await getGallery(
      { page: queryRole.page, limit: queryRole.limit },
      { [queryRole.sortBy]: sortRole[queryRole.with] || -1 },
      queryRole.search
    );

    return response(200, "Get gallery data successfully", galleries);
  } catch (error) {
    return response(500, "Internal Server Error", null, {
      error: "Failed to get galleries data",
    });
  }
}

export async function PATCH(request) {
  try {
    const data = await request.json();

    if (!data?._id)
      return response(400, "Bad Request", null, { error: "ID is required" });

    const result = await updateGalleryById(data);

    return response(200, "Update gallery data successfully", result);
  } catch (error) {
    return response(500, "Internal Server Error", null, {
      error: "Failed to update data",
    });
  }
}

export async function POST(request) {
  try {
    const body = await request.json();

    const result = await Promise.all(
      body.data.map(async (item) => await deleteMedia(item))
    );

    return response(200, "Delete media successfully", result);
  } catch (error) {
    return response(500, "Internal Server Error", null, {
      error: "Failed to Delete Media",
    });
  }
}
