import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export const dynamic = 'force-dynamic';

export async function GET() {
  const stations = await prisma.pOSStation.findMany({
    where: { isActive: true },
    orderBy: { name: 'asc' },
  });
  return NextResponse.json({ stations });
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { id, name, stationType, location, layoutConfig, printerConfig, isActive } = body;

    if (id) {
      const station = await prisma.pOSStation.update({
        where: { id },
        data: { name, stationType, location, layoutConfig, printerConfig, isActive },
      });
      return NextResponse.json({ station });
    }

    const station = await prisma.pOSStation.create({
      data: {
        name: name || 'Register 1',
        stationType: stationType || 'register',
        location: location || 'Main',
        layoutConfig: layoutConfig || {},
        printerConfig: printerConfig || {},
      },
    });
    return NextResponse.json({ station }, { status: 201 });
  } catch (error) {
    console.error('Station error:', error);
    return NextResponse.json({ error: 'Failed to save station' }, { status: 500 });
  }
}
