import _ from "lodash";
import { prisma } from "@/lib";
import { NextResponse } from "next/server";
import { sendNotificationInvestmentAddNews } from "@/lib/mobile/notification/notification-add-news-investment";
import { PAGINATION_DEFAULT_TAKE } from "@/lib/constans-value/constansValue";

export { POST, GET, DELETE };

async function POST(request: Request, { params }: { params: { id: string } }) {
  const { id } = params;
  const { data } = await request.json();
  let fixData;

  console.log("id", id);
  console.log("data", data);

  try {
    if (data && data.imageId) {
      const createWithFile = await prisma.beritaInvestasi.create({
        data: {
          investasiId: id,
          title: _.startCase(data.title),
          deskripsi: data.deskripsi,
          imageId: data.imageId,
        },
        select: {
          investasiId: true,
          investasi: {
            select: {
              title: true,
              authorId: true,
            },
          },
        },
      });

      await sendNotificationInvestmentAddNews({
        invesmentId: createWithFile.investasiId,
        senderId: createWithFile.investasi.authorId as string,
        title: createWithFile.investasi.title,
      });

      fixData = createWithFile;
    } else {
      const createWitOutFile = await prisma.beritaInvestasi.create({
        data: {
          investasiId: id,
          title: _.startCase(data.title),
          deskripsi: data.deskripsi,
        },
        select: {
          investasiId: true,
          investasi: {
            select: {
              title: true,
              authorId: true,
            },
          },
        },
      });

      await sendNotificationInvestmentAddNews({
        invesmentId: createWitOutFile.investasiId,
        senderId: createWitOutFile.investasi.authorId as string,
        title: createWitOutFile.investasi.title,
      });

      fixData = createWitOutFile;
    }

    return NextResponse.json({
      status: 201,
      success: true,
      message: "Berita berhasil ditambahkan",
      data: fixData,
    });
  } catch (error) {
    console.log(["ERROR"], error);
    return NextResponse.json({
      status: 500,
      success: false,
      error: "Gagal menambah berita",
    });
  }
}

async function GET(request: Request, { params }: { params: { id: string } }) {
  const { id } = params;
  console.log("id", id);
  const { searchParams } = new URL(request.url);
  const category = searchParams.get("category");
  const page = Number(searchParams.get("page")) || 1;
  const takeData = PAGINATION_DEFAULT_TAKE;
  const skipData = page * takeData - takeData;

  let fixData;
  let meta = null;
  
  try {
    if (category === "one-news") {
      const data = await prisma.beritaInvestasi.findFirst({
        where: {
          id: id,
        },
        include: {
          investasi: {
            select: {
              authorId: true,
            },
          },
        },
      });

      const authorId = data?.investasi?.authorId;
      const newData = {
        ...data,
        authorId,
      };

      fixData = newData;
    } else if (category === "all-news") {
      const newsData = await prisma.beritaInvestasi.findMany({
        orderBy: {
          updatedAt: "desc",
        },
        where: {
          investasiId: id,
          active: true,
        },
        take: takeData,
        skip: skipData,
      });

      const totalData = await prisma.beritaInvestasi.count({
        where: {
          investasiId: id,
          active: true,
        },
      });

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

      fixData = newsData;
      
      meta = {
        currentPage: page,
        totalData: totalData,
        totalPage: totalPages,
        dataPerPage: takeData,
      };
    }

    return NextResponse.json({
      status: 200,
      success: true,
      message: "Berita berhasil diambil",
      data: fixData,
      ...(meta && { meta }),
    });
  } catch (error) {
    console.log("[ERROR]", error);
    return NextResponse.json({
      status: 500,
      success: false,
      error: "Gagal mengambil berita",
    });
  }
}

async function DELETE(
  request: Request,
  { params }: { params: { id: string } },
) {
  const { id } = params;
  console.log("id", id);
  try {
    const deleteData = await prisma.beritaInvestasi.delete({
      where: {
        id: id,
      },
    });

    console.log("DELETE", deleteData);

    return NextResponse.json({
      status: 200,
      success: true,
      message: "Berita berhasil dihapus",
    });
  } catch (error) {
    console.log("[ERROR]", error);
    return NextResponse.json({
      status: 500,
      success: false,
      error: "Gagal menghapus berita",
    });
  }
}
