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


// HAPUS DETAIL PROJECT
export async function DELETE(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params;
        const { idProject, user } = (await request.json());

        const userMobile = await funGetUserById({ id: String(user) })

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

        const data = await prisma.projectTask.count({
            where: {
                id: id,
            },
        });

        if (data == 0) {
            return NextResponse.json(
                {
                    success: false,
                    message: "Hapus tahapan kegiatan gagal, data tidak ditemukan",
                },
                { status: 200 }
            );
        }

        const update = await prisma.projectTask.update({
            where: {
                id: id,
            },
            data: {
                isActive: false,
            },
        });

        const dataTask = await prisma.projectTask.findMany({
            where: {
                isActive: true,
                idProject: idProject,
            }
        })

        const semua = dataTask.length
        const selesai = dataTask.filter((item) => item.status == 1).length
        const prosess = Math.ceil((selesai / semua) * 100)
        let statusProject = 1

        if (prosess == 100) {
            statusProject = 2
        } else if (prosess == 0) {
            statusProject = 0
        }


        const updProject = await prisma.project.update({
            where: {
                id: idProject
            },
            data: {
                status: statusProject
            }
        })

        // create log user
        const log = await createLogUserMobile({ act: 'DELETE', desc: 'User menghapus tahapan kegiatan', table: 'projectTask', data: String(id), user: userMobile.id })


        return NextResponse.json(
            {
                success: true,
                message: "Tahapan kegiatan berhasil dihapus",
            },
            { status: 200 }
        );
    } catch (error) {
        console.error(error);
        return NextResponse.json({ success: false, message: "Gagal menghapus tahapan kegiatan, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
    }
}


// EDIT STATUS DETAIL PROJECT
export async function PUT(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params;
        const { status, idProject, user } = (await request.json());
        const userMobile = await funGetUserById({ id: String(user) })

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

        const data = await prisma.projectTask.count({
            where: {
                id
            }
        })

        if (data == 0) {
            return NextResponse.json(
                {
                    success: false, message: "Gagal mendapatkan kegiatan, data tidak ditemukan",
                },
                { status: 200 }
            );
        }

        const dataCreate = await prisma.projectTask.update({
            where: {
                id
            },
            data: {
                status: status
            }
        })


        // const cek progress 
        const dataTask = await prisma.projectTask.findMany({
            where: {
                isActive: true,
                idProject: idProject,
            }
        })

        const semua = dataTask.length
        const selesai = dataTask.filter((item) => item.status == 1).length
        const prosess = Math.ceil((selesai / semua) * 100)
        let statusProject = 1

        if (prosess == 100) {
            statusProject = 2
        } else if (prosess == 0) {
            statusProject = 0
        }


        const update = await prisma.project.update({
            where: {
                id: idProject
            },
            data: {
                status: statusProject
            }
        })

        // create log user
        const log = await createLogUserMobile({ act: 'UPDATE', desc: 'User mengupdate status tahapan kegiatan', table: 'projectTask', data: String(id), user: userMobile.id })

        return NextResponse.json({ success: true, message: "Status tahapan kegiatan berhasil diupdate" }, { status: 200 });

    } catch (error) {
        console.error(error);
        return NextResponse.json({ success: false, message: "Gagal mengupdate status tahapan kegiatan, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
    }
}


// GET ONE DETAIL PROJECT
export async function GET(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params;
        const { searchParams } = new URL(request.url);
        const user = searchParams.get("user");
        const kategori = searchParams.get("cat");
        const userMobile = await funGetUserById({ id: String(user) })

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

        let dataFix
        const data = await prisma.projectTask.findUnique({
            where: {
                id: String(id),
                isActive: true
            }
        })

        const fixData = { ...data, dateStart: moment(data?.dateStart).format('YYYY-MM-DD'), dateEnd: moment(data?.dateEnd).format('YYYY-MM-DD') }

        if (!data) {
            return NextResponse.json(
                {
                    success: false, message: "Gagal mendapatkan kegiatan, data tidak ditemukan",
                },
                { status: 200 }
            );
        }

        if (kategori == "detailTask") {
            const dataDetail = await prisma.projectTaskDetail.findMany({
                where: {
                    idTask: String(id)
                },
                orderBy: {
                    date: "asc"
                }
            })

            const dataDetailFix = dataDetail.map((data: any) => ({
                ...data,
                date: moment(data?.date).format('DD-MM-YYYY'),
                timeStart: data.timeStart == null ? "" : moment.utc(data.timeStart).format("HH:mm"),
                timeEnd: data.timeEnd == null ? "" : moment.utc(data.timeEnd).format("HH:mm")
            }))

            dataFix = dataDetailFix
        } else {
            dataFix = fixData
        }

        return NextResponse.json({ success: true, message: "Detail kegiatan berhasil ditemukan", data: dataFix }, { status: 200 });
    } catch (error) {
        console.error(error);
        return NextResponse.json({ success: false, message: "Gagal mendapatkan kegiatan, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
    }
}


// EDIT DETAIL PROJECT
export async function POST(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params;
        const { title, dateStart, dateEnd, user, dataDetail } = (await request.json());
        const userMobile = await funGetUserById({ id: String(user) })

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

        const dataTask = await prisma.projectTask.count({
            where: {
                id
            }
        })

        if (dataTask == 0) {
            return NextResponse.json(
                {
                    success: false, message: "Gagal mendapatkan kegiatan, data tidak ditemukan",
                },
                { status: 200 }
            );
        }

        const data = await prisma.projectTask.update({
            where: {
                id
            },
            data: {
                title,
                dateStart: new Date(dateStart),
                dateEnd: new Date(dateEnd),
            }
        })

        const dataDetailDelete = await prisma.projectTaskDetail.deleteMany({
            where: {
                idTask: id
            }
        })

        if (dataDetail.length > 0) {
            const dataDetailFix = dataDetail.map((v: any) => ({
                ...v,
                idTask: id,
                date: new Date(v.date),
                timeStart: v.timeStart == null ? null : new Date(new Date('1970-01-01 ' + v.timeStart).getTime() - (new Date('1970-01-01 ' + v.timeStart).getTimezoneOffset() * 60000)).toISOString(),
                timeEnd: v.timeEnd == null ? null : new Date(new Date('1970-01-01 ' + v.timeEnd).getTime() - (new Date('1970-01-01 ' + v.timeEnd).getTimezoneOffset() * 60000)).toISOString(),
            }))

            const dataDetailCreate = await prisma.projectTaskDetail.createMany({
                data: dataDetailFix
            })
        }

        // create log user
        const log = await createLogUserMobile({ act: 'UPDATE', desc: 'User mengupdate tahapan kegiatan', table: 'projectTask', data: String(id), user: userMobile.id })

        return NextResponse.json({ success: true, message: "Detail tahapan kegiatan berhasil diupdate" }, { status: 200 });

    } catch (error) {
        console.error(error);
        return NextResponse.json({ success: false, message: "Gagal mengupdate detail tahapan kegiatan, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
    }
}