import { eq } from 'drizzle-orm';
import { headers } from 'next/headers';
import { NextResponse } from 'next/server';
import { db } from '@/db/drizzle';
import { testimony } 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: 'Testimony ID is required' },
        { status: 400 }
      );
    }

    const formData = await req.formData();

    const name = formData.get('name')?.toString() ?? '';
    const position = formData.get('position')?.toString() ?? '';
    const company = formData.get('company')?.toString() ?? '';
    const content = formData.get('content')?.toString() ?? '';
    const image = formData.get('image')?.toString() ?? '';

    const updatedTestimony = await db
      .update(testimony)
      .set({
        name,
        position,
        company,
        content,
        image,
        updatedAt: new Date(),
      })
      .where(eq(testimony.id, id))
      .execute();

    return NextResponse.json(updatedTestimony[0], { status: 200 });
  } catch (error) {
    console.error('Error updating testimony:', error);
    return NextResponse.json(
      { message: error.message || 'Failed to update testimony' },
      { 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: 'Testimony ID is required' },
        { status: 400 }
      );
    }

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

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