import { eq } from 'drizzle-orm';
import { headers } from 'next/headers';
import { NextResponse } from 'next/server';
import { db } from '@/db/drizzle';
import { branch } 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 || session.user.role !== 'admin') {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

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

    const formData = await req.formData();

    const name = formData.get('name')?.toString() ?? '';
    const phone = formData.get('phone')?.toString() ?? '';
    const email = formData.get('email')?.toString() ?? '';
    const address = formData.get('address')?.toString() ?? '';
    const location = formData.get('location')?.toString() ?? '';
    const workingHours = formData.get('workingHours')?.toString() ?? '';

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

    const updatedBranch = await db
      .update(branch)
      .set({
        name,
        phone,
        email,
        address,
        location: location ? JSON.parse(location) : null,
        workingHours,
        updatedAt: new Date(),
      })
      .where(eq(branch.id, id))
      .execute();

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