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

// GET - Tüm metro istasyonlarını getir
export async function GET() {
  try {
    const stations = await prisma.metroStation.findMany({
      orderBy: { order: 'asc' },
    });

    return NextResponse.json(stations);
  } catch (error) {
    console.error('Stations fetch error:', error);
    return NextResponse.json(
      { error: 'İstasyonlar alınırken hata oluştu' },
      { status: 500 }
    );
  }
}

// POST - Yeni istasyon ekle (Auth gerekli)
export async function POST(request: NextRequest) {
  return withAuth(request, async () => {
    try {
      const data = await request.json();

      const station = await prisma.metroStation.create({
        data: {
          name: data.name,
          status: data.status,
          progress: data.progress,
          order: data.order,
          description: data.description || data.estimatedCompletion,
        },
      });

      return NextResponse.json(station, { status: 201 });
    } catch (error) {
      console.error('Station create error:', error);
      return NextResponse.json(
        { error: 'İstasyon oluşturulurken hata oluştu' },
        { status: 500 }
      );
    }
  });
}

// PUT - İstasyon güncelle (Auth gerekli)
export async function PUT(request: NextRequest) {
  return withAuth(request, async () => {
    try {
      const data = await request.json();

      const station = await prisma.metroStation.update({
        where: { id: data.id },
        data: {
          name: data.name,
          status: data.status,
          progress: data.progress,
          order: data.order,
          description: data.description || data.estimatedCompletion,
        },
      });

      return NextResponse.json(station);
    } catch (error) {
      console.error('Station update error:', error);
      return NextResponse.json(
        { error: 'İstasyon güncellenirken hata oluştu' },
        { status: 500 }
      );
    }
  });
}

// DELETE - İstasyon sil (Auth gerekli)
export async function DELETE(request: NextRequest) {
  return withAuth(request, async () => {
    try {
      const { searchParams } = new URL(request.url);
      const id = searchParams.get('id');

      if (!id) {
        return NextResponse.json({ error: 'ID gerekli' }, { status: 400 });
      }

      await prisma.metroStation.delete({
        where: { id: parseInt(id) },
      });

      return NextResponse.json({ message: 'İstasyon silindi' });
    } catch (error) {
      console.error('Station delete error:', error);
      return NextResponse.json(
        { error: 'İstasyon silinirken hata oluştu' },
        { status: 500 }
      );
    }
  });
}
