export const dynamic = 'force-dynamic';

import { NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/authOptions';

export async function GET() {
  try {
    const machines = await prisma.machine.findMany({ orderBy: { name: 'asc' } });
    return NextResponse.json(machines);
  } catch (error) {
    console.error('Error fetching machines:', error);
    return NextResponse.json({ error: 'Failed to fetch machines' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    const userId = (session.user as { id?: string })?.id;
    if (!userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { name, maxRpm, maxFeedRate, horsepower, spindleType, controller, description } = body ?? {};

    const machine = await prisma.userMachine.create({
      data: {
        userId,
        name,
        maxRpm: parseFloat(maxRpm),
        maxFeedRate: parseFloat(maxFeedRate),
        horsepower: parseFloat(horsepower),
        spindleType: spindleType ?? null,
        controller: controller ?? null,
        description: description ?? null,
      },
    });

    return NextResponse.json(machine, { status: 201 });
  } catch (error) {
    console.error('Error creating machine:', error);
    return NextResponse.json({ error: 'Failed to create machine' }, { status: 500 });
  }
}
