import { prisma } from "@/module/_global";
import { funGetUserById } from "@/module/auth";
import _ from "lodash";
import moment from "moment";
import { NextResponse } from "next/server";

// GET indicator dot per bulan (tanggal mana saja yang ada event)
export async function GET(request: Request) {
    try {
        const { searchParams } = new URL(request.url);
        const user = searchParams.get("user");
        const date = searchParams.get("date");

        const userMobile = await funGetUserById({ id: String(user) });
        if (!userMobile.id || userMobile.id === "null") {
            return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 200 });
        }

        const idVillage = userMobile.idVillage;
        const awalDate = moment(date).format("YYYY-MM") + "-01";
        const akhirDate = moment(awalDate).add(1, "M").format("YYYY-MM-DD");

        // Tanggal dengan event kalender divisi
        const calendarDates = await prisma.divisionCalendarReminder.findMany({
            where: {
                isActive: true,
                dateStart: {
                    gte: new Date(awalDate),
                    lt: new Date(akhirDate),
                },
                Division: {
                    idVillage,
                    isActive: true,
                },
                DivisionCalendar: {
                    isActive: true,
                },
            },
            select: { dateStart: true },
        });

        // Tanggal dengan task project se-village (ambil semua task yang overlap dengan bulan ini)
        const taskDates = await prisma.projectTask.findMany({
            where: {
                isActive: true,
                dateStart: { lt: new Date(akhirDate) },
                dateEnd: { gte: new Date(awalDate) },
                Project: {
                    isActive: true,
                    idVillage: String(idVillage),
                },
            },
            select: { dateStart: true, dateEnd: true },
        });

        // Expand setiap task menjadi array tanggal per hari dalam range bulan
        const taskExpandedDates: string[] = [];
        for (const task of taskDates) {
            let cur = moment(task.dateStart);
            const end = moment(task.dateEnd);
            const monthStart = moment(awalDate);
            const monthEnd = moment(akhirDate);
            while (cur.isSameOrBefore(end)) {
                if (cur.isSameOrAfter(monthStart) && cur.isBefore(monthEnd)) {
                    taskExpandedDates.push(cur.format("YYYY-MM-DD"));
                }
                cur.add(1, 'day');
            }
        }

        const calendarResult = _.uniq(calendarDates.map((v) => moment(v.dateStart).format("YYYY-MM-DD"))).sort();
        const taskResult = _.uniq(taskExpandedDates).sort();

        return NextResponse.json({
            success: true,
            message: "Berhasil mendapatkan indicator kalender",
            data: { calendar: calendarResult, task: taskResult }
        }, { status: 200 });
    } catch (error) {
        console.error(error);
        return NextResponse.json({ success: false, message: "Gagal mendapatkan indicator kalender (error: 500)" }, { status: 500 });
    }
}
