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

export async function PUT(req: Request, params: { params: { id: string } }) {
  const session = await auth.api.getSession({
    headers: await headers(),
  });
  if (!session?.user) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  try {
    const { id } = await params.params;
    if (!id) {
      return NextResponse.json(
        { message: 'Hero Content ID is required' },
        { status: 400 }
      );
    }

    const formData = await req.formData();

    const title = formData.get('title')?.toString() ?? '';
    const subtitle = formData.get('subtitle')?.toString() ?? '';
    const description = formData.get('description')?.toString() ?? '';
    const imagePath = formData.get('imagePath')?.toString() ?? '';
    const buttonText = formData.get('buttonText')?.toString() ?? '';
    const buttonLink = formData.get('buttonLink')?.toString() ?? '';
    const isActive = formData.get('isActive')?.toString() === 'true';

    const updatedHeroContent = await db
      .update(heroContent)
      .set({
        title,
        subtitle,
        description,
        imagePath,
        buttonText,
        buttonLink,
        isActive,
        updatedAt: new Date(),
      })
      .where(eq(heroContent.id, id))
      .execute();

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

export async function DELETE(req: Request, params: { params: { id: string } }) {
  const session = await auth.api.getSession({
    headers: await headers(),
  });
  if (!session?.user) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  try {
    const { id } = await params.params;
    if (!id) {
      return NextResponse.json(
        { message: 'Hero Content ID is required' },
        { status: 400 }
      );
    }

    await db.delete(heroContent).where(eq(heroContent.id, id)).execute();

    return NextResponse.json({ message: 'Hero Content deleted successfully' }, { status: 200 });
  } catch (error) {
    console.error('Error deleting hero content:', error);
    return NextResponse.json(
      { message: error.message || 'Failed to delete hero content' },
      { status: 500 }
    );
  }
}
