import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { unlink, rm } from 'fs/promises';
import path from 'path';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const project = await db.photoProject.findUnique({
      where: { id },
      include: {
        edits: {
          orderBy: { order: 'asc' },
        },
      },
    });

    if (!project) {
      return NextResponse.json({ error: 'المشروع غير موجود' }, { status: 404 });
    }

    return NextResponse.json(project);
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'خطأ في جلب المشروع';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    const project = await db.photoProject.findUnique({
      where: { id },
      include: { edits: true },
    });

    if (!project) {
      return NextResponse.json({ error: 'المشروع غير موجود' }, { status: 404 });
    }

    // Delete associated files
    for (const edit of project.edits) {
      try {
        if (edit.editedPath) {
          const filepath = path.join(process.cwd(), 'public', edit.editedPath);
          await unlink(filepath);
        }
      } catch {
        // Ignore file not found
      }
    }

    // Delete from database (cascade will delete edits)
    await db.photoProject.delete({
      where: { id },
    });

    return NextResponse.json({ success: true });
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'خطأ في حذف المشروع';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}