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 GET(req: Request) {
  const session = await auth.api.getSession({
    headers: req.headers,
  });

  if (!session?.user || session.user.role !== 'admin') {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  try {
    const branches = await db.select().from(branch);
    return NextResponse.json(branches);
  } catch (error) {
    console.error('Error fetching branches:', error);
    return NextResponse.json(
      { message: 'Failed to fetch branches' },
      { status: 500 }
    );
  }
}

export async function POST(req: Request) {
  const session = await auth.api.getSession({
    headers: req.headers,
  });

  if (!session?.user || session.user.role !== 'admin') {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  try {
    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 newBranch = await db.insert(branch).values({
      id: crypto.randomUUID(),
      name,
      phone,
      email,
      address,
      location: location ? JSON.parse(location) : null,
      workingHours,
      createdAt: new Date(),
      updatedAt: new Date(),
    });

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