import { eq, sql } from 'drizzle-orm';
import { headers } from 'next/headers';
import { NextResponse } from 'next/server';
import { db } from '@/db/drizzle';
import { client, image, moreProject, project } from '@/db/schema';
import { auth } from '@/lib/auth';
import { handleImageUpload } from '@/lib/image-upload';
import { createSlug } from '@/lib/utils';

export async function GET(req: Request) {
  const session = await auth.api.getSession({
    headers: req.headers,
  });

  if (!session?.user || session.user.role !== 'admin') {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  try {
    const projectsWithCounts = await db
      .select({
        ...project,
        clientName: client.name,
        clientId: client.id,
        clientImage: client.image,
        imageCount: sql<number>`(SELECT COUNT(*) FROM image WHERE image.projectId = project.id)`,
        moreProjectCount: sql<number>`(SELECT COUNT(*) FROM more_project WHERE more_project.projectId = project.id)`,
      })
      .from(project)
      .leftJoin(client, eq(project.clientId, client.id));

    return NextResponse.json(projectsWithCounts);
  } catch (error) {
    console.error('Error fetching projects:', error);
    return NextResponse.json(
      { message: 'Failed to fetch projects' },
      { status: 500 }
    );
  }
}

export async function POST(req: Request) {
  const session = await auth.api.getSession({
    headers: req.headers,
  });

  if (!session?.user || session.user.role !== 'admin') {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  try {
    const formData = await req.formData();

    const title = formData.get('title')?.toString() ?? '';
    const description = formData.get('description')?.toString() ?? '';
    const doc = formData.get('doc')?.toString() ?? '';
    const link = formData.get('link')?.toString() ?? '';
    const location = formData.get('location')?.toString() ?? '';
    const complete = formData.get('complete')?.toString() ?? '';
    const slug = createSlug(title) || '';
    const status = formData.get('status')?.toString() === 'true';
    const type = formData.get('type')?.toString() ?? '';
    const category = formData.get('category')?.toString() ?? '';
    const clientId = formData.get('clientId')?.toString() ?? '';
    const imageFile = formData.get('image_file') as File | null;

    // Validate required fields
    if (!title) {
      return NextResponse.json(
        { message: 'Title is required' },
        { status: 400 }
      );
    }

    const imagePath = await handleImageUpload(imageFile);

    const newProject = await db.insert(project).values({
      id: crypto.randomUUID(),
      title,
      description,
      doc,
      image: imagePath,
      link,
      location,
      complete,
      slug,
      status,
      type,
      category,
      clientId,
      createdAt: new Date(),
      updatedAt: new Date(),
    });

    return NextResponse.json(newProject, { status: 201 });
  } catch (error: any) {
    console.error('Error creating project:', error);
    return NextResponse.json(
      { message: error.message || 'Failed to create project' },
      { status: 500 }
    );
  }
}
