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

export async function GET(
  req: Request,
  { params }: { params: { id: string } }
) {
  try {
    const foundBlog = await db
      .select()
      .from(blog)
      .where(eq(blog.id, params.id))
      .limit(1);

    if (foundBlog.length === 0) {
      return NextResponse.json({ message: 'Blog not found' }, { status: 404 });
    }

    return NextResponse.json(foundBlog[0]);
  } catch (error) {
    console.error('Error fetching blog:', error);
    return NextResponse.json(
      { message: 'Failed to fetch blog' },
      { status: 500 }
    );
  }
}

export async function PUT(
  req: Request,
  { params }: { params: { id: string } }
) {
  try {
    const formData = await req.formData();

    const title = formData.get('title')?.toString() ?? '';
    const slug = formData.get('slug')?.toString() ?? '';
    const content = formData.get('content')?.toString() ?? '';
    const description = formData.get('description')?.toString() ?? '';
    const status = formData.get('status')?.toString() === 'true';
    const imageFile = formData.get('image') as File | null;
    const author = formData.get('author')?.toString() ?? '';
    const category = formData.get('category')?.toString() ?? '';
    const postBy = formData.get('postBy')?.toString() ?? '';
    const editBy = formData.get('editBy')?.toString() ?? '';

    const existingBlog = await db
      .select()
      .from(blog)
      .where(eq(blog.id, params.id))
      .limit(1);

    if (existingBlog.length === 0) {
      return NextResponse.json({ message: 'Blog not found' }, { status: 404 });
    }

    const imageUrl = await handleImageUpload(
      imageFile,
      existingBlog[0].image
    );

    const updatedBlog = await db
      .update(blog)
      .set({
        title,
        slug,
        content,
        description,
        status,
        image: imageUrl,
        author,
        category,
        postBy,
        editBy,
        updatedAt: new Date(),
      })
      .where(eq(blog.id, params.id));

    return NextResponse.json(updatedBlog, { status: 200 });
  } catch (error: any) {
    console.error('Error updating blog:', error);
    return NextResponse.json(
      { message: error.message || 'Failed to update blog' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  req: Request,
  { params }: { params: { id: string } }
) {
  try {
    await db.delete(blog).where(eq(blog.id, params.id));
    return NextResponse.json({ message: 'Blog deleted successfully' });
  } catch (error) {
    console.error('Error deleting blog:', error);
    return NextResponse.json(
      { message: 'Failed to delete blog' },
      { status: 500 }
    );
  }
}