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

// GET: daftar file yang terlampir pada DivisionProjectTask
// [id] = DivisionProjectTask.id
export async function GET(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params;
      const { searchParams } = new URL(request.url);
      const userMobile = searchParams.get("user");

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

      const data = await prisma.divisionProjectTaskFile.findMany({
         where: {
            idTask: id,
            isActive: true,
         },
         select: {
            id: true,
            DivisionProjectFile: {
               select: {
                  id: true,
                  ContainerFileDivision: {
                     select: {
                        name: true,
                        extension: true,
                        idStorage: true,
                     },
                  },
               },
            },
         },
         orderBy: { createdAt: "asc" },
      });

      const result = data.map((v) => ({
         id: v.id,
         idFile: v.DivisionProjectFile.id,
         name: v.DivisionProjectFile.ContainerFileDivision.name,
         extension: v.DivisionProjectFile.ContainerFileDivision.extension,
         idStorage: v.DivisionProjectFile.ContainerFileDivision.idStorage,
      }));

      return NextResponse.json({ success: true, message: "Berhasil mendapatkan file tugas", data: result }, { status: 200 });
   } catch (error) {
      console.error(error);
      return NextResponse.json({ success: false, message: "Gagal mendapatkan file tugas (error: 500)", reason: (error as Error).message }, { status: 500 });
   }
}

// POST: upload file baru ke DivisionProjectTask
// [id] = DivisionProjectTask.id
export async function POST(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params;
      const body = await request.formData();
      const data = JSON.parse(body.get("data") as string);

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

      const task = await prisma.divisionProjectTask.findUnique({
         where: { id },
         select: { id: true, idProject: true, idDivision: true },
      });

      if (!task) {
         return NextResponse.json({ success: false, message: "Tugas tidak ditemukan" }, { status: 200 });
      }

      const hasCekFile = body.has("file0");
      if (!hasCekFile) {
         return NextResponse.json({ success: false, message: "Tidak ada file yang dikirim" }, { status: 200 });
      }

      body.delete("data");
      for (const [key] of body.entries()) {
         if (!key.startsWith("file")) continue;

         const file = body.get(key) as File;
         const fExt = file.name.split(".").pop();
         const fName = file.name.replace("." + fExt, "");

         const upload = await funUploadFile({ file, dirId: DIR.task });
         if (!upload.success) continue;

         const container = await prisma.containerFileDivision.create({
            data: {
               idDivision: task.idDivision,
               name: fName,
               extension: String(fExt),
               idStorage: upload.data.id,
            },
            select: { id: true },
         });

         const divFile = await prisma.divisionProjectFile.create({
            data: {
               idProject: task.idProject,
               idDivision: task.idDivision,
               idFile: container.id,
               createdBy: user.id,
            },
            select: { id: true },
         });

         await prisma.divisionProjectTaskFile.create({
            data: {
               idTask: id,
               idFile: divFile.id,
            },
         });
      }

      await createLogUserMobile({ act: "CREATE", desc: "User menambah file pada tugas divisi", table: "divisionProjectTask", data: id, user: user.id });

      return NextResponse.json({ success: true, message: "Berhasil menambahkan file" }, { status: 200 });
   } catch (error) {
      console.error(error);
      return NextResponse.json({ success: false, message: "Gagal menambahkan file (error: 500)", reason: (error as Error).message }, { status: 500 });
   }
}

// PATCH: link DivisionProjectFile yang sudah ada ke DivisionProjectTask
// Body: { user, idFile }  — idFile = DivisionProjectFile.id
// [id] = DivisionProjectTask.id
export async function PATCH(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params;
      const { user: userId, idFile } = await request.json();

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

      const task = await prisma.divisionProjectTask.findUnique({
         where: { id },
         select: { id: true },
      });
      if (!task) {
         return NextResponse.json({ success: false, message: "Tugas tidak ditemukan" }, { status: 200 });
      }

      const file = await prisma.divisionProjectFile.findUnique({
         where: { id: idFile },
         select: { id: true },
      });
      if (!file) {
         return NextResponse.json({ success: false, message: "File tidak ditemukan" }, { status: 200 });
      }

      const existing = await prisma.divisionProjectTaskFile.findFirst({
         where: { idTask: id, idFile, isActive: true },
      });
      if (existing) {
         return NextResponse.json({ success: false, message: "File sudah terlampir pada tugas ini" }, { status: 200 });
      }

      await prisma.divisionProjectTaskFile.create({
         data: { idTask: id, idFile },
      });

      await createLogUserMobile({ act: "CREATE", desc: "User melampirkan file divisi ke tugas", table: "divisionProjectTask", data: id, user: user.id });

      return NextResponse.json({ success: true, message: "Berhasil melampirkan file" }, { status: 200 });
   } catch (error) {
      console.error(error);
      return NextResponse.json({ success: false, message: "Gagal melampirkan file (error: 500)", reason: (error as Error).message }, { status: 500 });
   }
}

// DELETE: hapus lampiran file dari DivisionProjectTask (hapus junction record saja)
// [id] = DivisionProjectTaskFile.id
export async function DELETE(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params;
      const { user: userId } = await request.json();

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

      const junction = await prisma.divisionProjectTaskFile.findUnique({
         where: { id },
         select: { id: true, idTask: true },
      });
      if (!junction) {
         return NextResponse.json({ success: false, message: "Data tidak ditemukan" }, { status: 200 });
      }

      await prisma.divisionProjectTaskFile.delete({ where: { id } });

      await createLogUserMobile({ act: "DELETE", desc: "User menghapus lampiran file dari tugas divisi", table: "divisionProjectTask", data: junction.idTask, user: user.id });

      return NextResponse.json({ success: true, message: "Berhasil menghapus lampiran file" }, { status: 200 });
   } catch (error) {
      console.error(error);
      return NextResponse.json({ success: false, message: "Gagal menghapus lampiran file (error: 500)", reason: (error as Error).message }, { status: 500 });
   }
}
