import _ from "lodash";
import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { PAGINATION_DEFAULT_TAKE } from "@/lib/constans-value/constansValue";

export { GET, PUT };

async function GET(
  request: Request,
  { params }: { params: { id: string; status: string } }
) {
  try {
    const { id, status } = params;
    const fixStatusName = _.startCase(status);

    const { searchParams } = new URL(request.url);
    const page = Number(searchParams.get("page")) || 1;
    const takeData = PAGINATION_DEFAULT_TAKE
    const skipData = page * takeData - takeData;

    let data;
    let totalCount;

    if (fixStatusName === "Publish") {
      data = await prisma.voting.findMany({
        where: {
          authorId: id,
          isActive: true,
          akhirVote: {
            gte: new Date(),
          },
          Voting_Status: {
            name: fixStatusName,
          },
        },
        take: takeData,
        skip: skipData,
      });

      totalCount = await prisma.voting.count({
        where: {
          authorId: id,
          isActive: true,
          akhirVote: {
            gte: new Date(),
          },
          Voting_Status: {
            name: fixStatusName,
          },
        },
      });
    } else {
      data = await prisma.voting.findMany({
        where: {
          authorId: id,
          Voting_Status: {
            name: fixStatusName,
          },
        },
        take: takeData,
        skip: skipData,
      });

      totalCount = await prisma.voting.count({
        where: {
          authorId: id,
          Voting_Status: {
            name: fixStatusName,
          },
        },
      });
    }

    const totalPages = Math.ceil(totalCount / takeData);

    return NextResponse.json({
      success: true,
      message: "Success get voting",
      data: data,
      pagination: {
        currentPage: page,
        totalPages: totalPages,
        totalData: totalCount,
        dataPerPage: takeData,
      },
    });
  } catch (error) {
    console.log("[ERROR]", error);
    return NextResponse.json({
      success: false,
      message: "Error get voting",
      reason: (error as Error).message,
    });
  }
}

async function PUT(
  request: Request,
  { params }: { params: { id: string; status: string } }
) {
  try {
    const { id, status } = params;
    const fixStatusName = _.startCase(status);

    const checkData = await prisma.voting.findFirst({
      where: {
        id: id,
      },
      select: {
        id: true,
        Voting_Status: {
          select: {
            name: true,
          },
        },
      },
    });

    if (!checkData)
      return NextResponse.json({
        success: false,
        message: "Voting tidak ditemukan",
      });

    if (checkData?.Voting_Status?.name === "Publish") {
      return NextResponse.json({
        success: false,
        message: "Voting telah terpublish",
      });
    }

    const checkStatus = await prisma.masterStatus.findFirst({
      where: {
        name: fixStatusName,
      },
    });

    if (!checkStatus)
      return NextResponse.json({
        success: false,
        message: "Status tidak ditemukan",
      });

    const updateData = await prisma.voting.update({
      where: {
        id: id,
      },
      data: {
        voting_StatusId: checkStatus.id,
      },
    });

    return NextResponse.json({
      success: true,
      message: "Success update voting",
      data: updateData,
    });
  } catch (error) {
    console.log("[ERROR]", error);
    return NextResponse.json({
      success: false,
      message: "Error update voting",
      reason: (error as Error).message,
    });
  }
}
