import { eq } from 'drizzle-orm';
import { NextResponse } from 'next/server';
import { headers } from 'next/headers';
import { db } from '@/db/drizzle';
import { service } from '@/db/schema';
import { handleImageUpload } from '@/lib/image-upload';
import { auth } from '@/lib/auth';



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 services = await db.select().from(service);
    return NextResponse.json(services);
  } catch (error) {
    console.error('Error fetching services:', error);
    return NextResponse.json(
      { message: 'Failed to fetch services' },
      { 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 name = formData.get('name')?.toString() ?? '';
    const summary = formData.get('summary')?.toString() ?? '';
    const description = formData.get('description')?.toString() ?? '';
    const status = formData.get('status')?.toString() === 'true';
    const imageFile = formData.get('image_file') as File | null;

    // Validate required fields
    if (!(name && description)) {
      return NextResponse.json(
        { message: 'Name and description are required' },
        { status: 400 }
      );
    }

    const imagePath = await handleImageUpload(imageFile);

    const newService = await db.insert(service).values({
      id: crypto.randomUUID(),
      name,
      summary,
      description,
      image: imagePath,
      status,
      createdAt: new Date(),
      updatedAt: new Date(),
    });

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

export async function PUT(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 url = new URL(req.url);
    const id = url.pathname.split('/').pop();

    if (!id) {
      return NextResponse.json(
        { message: 'Service ID is required' },
        { status: 400 }
      );
    }

    const formData = await req.formData();

    const name = formData.get('name')?.toString() ?? '';
    const description = formData.get('description')?.toString() ?? '';
    const status = formData.get('status')?.toString() === 'true';
    const imageFile = formData.get('image_file') as File | null;
    const existingImage = formData.get('existing_image')?.toString() ?? null;

    // Validate required fields
    if (!(name && description)) {
      return NextResponse.json(
        { message: 'Name and description are required' },
        { status: 400 }
      );
    }

    const imagePath = await handleImageUpload(
      imageFile,
      existingImage
    );

    const updatedService = await db
      .update(service)
      .set({
        name,
        description,
        image: imagePath,
        status,
        updatedAt: new Date(),
      })
      .where(eq(service.id, id))
      .execute();

    return NextResponse.json(updatedService[0], { status: 200 });
  } catch (error: any) {
    console.error('Error updating service:', error);
    return NextResponse.json(
      { message: error.message || 'Failed to update service' },
      { status: 500 }
    );
  }
}
