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 ProjectTask
// [id] = ProjectTask.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.projectTaskFile.findMany({
         where: {
            idTask: id,
            isActive: true,
         },
         select: {
            id: true,
            ProjectFile: {
               select: {
                  id: true,
                  name: true,
                  extension: true,
                  idStorage: true,
               },
            },
         },
         orderBy: { createdAt: "asc" },
      });

      const result = data.map((v) => ({
         id: v.id,           // ProjectTaskFile.id — dipakai untuk DELETE
         idFile: v.ProjectFile.id,  // ProjectFile.id — dipakai untuk filter duplikat di picker
         name: v.ProjectFile.name,
         extension: v.ProjectFile.extension,
         idStorage: v.ProjectFile.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 ProjectTask
// Membuat ProjectFile baru lalu membuat ProjectTaskFile (junction)
// [id] = ProjectTask.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.projectTask.findUnique({
         where: { id },
         select: { id: true, idProject: 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.project });
         if (!upload.success) continue;

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

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

      await createLogUserMobile({ act: "CREATE", desc: "User menambah file pada tugas kegiatan", table: "projectTask", 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 ProjectFile yang sudah ada ke ProjectTask
// Body: { user, idFile }  — idFile = ProjectFile.id
// [id] = ProjectTask.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.projectTask.findUnique({
         where: { id },
         select: { id: true },
      });
      if (!task) {
         return NextResponse.json({ success: false, message: "Tugas tidak ditemukan" }, { status: 200 });
      }

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

      // cek apakah sudah pernah di-link
      const existing = await prisma.projectTaskFile.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.projectTaskFile.create({
         data: { idTask: id, idFile },
      });

      await createLogUserMobile({ act: "CREATE", desc: "User melampirkan file kegiatan ke tugas", table: "projectTask", 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 ProjectTask (hapus junction record saja)
// [id] = ProjectTaskFile.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.projectTaskFile.findUnique({
         where: { id },
         select: { id: true, idTask: true },
      });
      if (!junction) {
         return NextResponse.json({ success: false, message: "Data tidak ditemukan" }, { status: 200 });
      }

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

      await createLogUserMobile({ act: "DELETE", desc: "User menghapus lampiran file dari tugas kegiatan", table: "projectTask", 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 });
   }
}
