import { NextResponse } from 'next/server';
import { db } from '@/db/drizzle';
import { heroContent } from '@/db/schema';

export async function GET() {
  try {
    const heroContents = await db.select().from(heroContent);
    return NextResponse.json(heroContents);
  } catch (error) {
    console.error('Error fetching hero contents:', error);
    return NextResponse.json(
      { message: 'Failed to fetch hero contents' },
      { status: 500 }
    );
  }
}

export async function POST(req: Request) {
  try {
    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 newHeroContent = await db.insert(heroContent).values({
      id: crypto.randomUUID(),
      title,
      subtitle,
      description,
      imagePath,
      buttonText,
      buttonLink,
      isActive,
      createdAt: new Date(),
      updatedAt: new Date(),
    });

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