import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "../../auth/[...nextauth]/route";
import { prisma } from "@/lib/prisma";

export async function GET(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { params } = context;
    const { id } = await params;
    
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: "Oturum bulunamadı" },
        { status: 401 }
      );
    }

    const user = await prisma.user.findFirst({
      where: { email: session.user.email },
    });

    if (!user) {
      return NextResponse.json(
        { error: "Kullanıcı bulunamadı" },
        { status: 401 }
      );
    }

    const route = await prisma.route.findFirst({
      where: { 
        id: id,
        userId: user.id 
      },
      include: {
        addresses: {
          orderBy: {
            order: 'asc'
          }
        }
      }
    });

    if (!route) {
      return NextResponse.json(
        { error: "Rota bulunamadı" },
        { status: 404 }
      );
    }

    return NextResponse.json(route);
  } catch (error) {
    console.error("Rota detayları alınırken hata oluştu:", error);
    return NextResponse.json(
      { error: "Rota detayları alınırken bir hata oluştu" },
      { status: 500 }
    );
  }
}

export async function PUT(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { params } = context;
    const { id } = await params;
    
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: "Oturum bulunamadı" },
        { status: 401 }
      );
    }

    const user = await prisma.user.findFirst({
      where: { email: session.user.email },
    });

    if (!user) {
      return NextResponse.json(
        { error: "Kullanıcı bulunamadı" },
        { status: 401 }
      );
    }

    const existingRoute = await prisma.route.findFirst({
      where: {
        id: id,
        userId: user.id
      },
      include: {
        addresses: true
      }
    });

    if (!existingRoute) {
      return NextResponse.json(
        { error: "Rota bulunamadı veya düzenleme yetkiniz yok" },
        { status: 404 }
      );
    }

    const { name, status, addresses } = await request.json();

    // Create a map of existing addresses by street for quick lookup
    const existingAddressMap = new Map();
    existingRoute.addresses.forEach(address => {
      existingAddressMap.set(address.street, address);
    });

    // Use a transaction to ensure atomicity
    const updatedRoute = await prisma.$transaction(async (tx) => {
      // Update route properties if provided
      const routeUpdate = {
        ...(name !== undefined && { name }),
        ...(status !== undefined && { status }),
      };

      // Update the route if there are properties to update
      if (Object.keys(routeUpdate).length > 0) {
        await tx.route.update({
          where: { id },
          data: routeUpdate
        });
      }

      // If addresses are provided, update them
      if (addresses && addresses.length > 0) {
        // Delete addresses that are no longer present
        const newStreetAddresses = addresses.map((a: { street: string }) => a.street);
        await tx.address.deleteMany({
          where: {
            routeId: id,
            street: { notIn: newStreetAddresses }
          }
        });

        // Process each address
        const addressPromises = addresses.map(async (address: {
          street: string;
          city?: string;
          postcode?: string;
          latitude?: number;
          longitude?: number;
        }, index: number) => {
          const existingAddress = existingAddressMap.get(address.street);
          
          if (existingAddress) {
            // Update existing address
            return tx.address.update({
              where: { id: existingAddress.id },
              data: {
                street: address.street,
                city: address.city || '',
                postcode: address.postcode || '',
                country: 'Switzerland',
                order: index,
                // Preserve latitude/longitude if not provided
                ...(address.latitude !== undefined ? { latitude: address.latitude } : {}),
                ...(address.longitude !== undefined ? { longitude: address.longitude } : {})
              }
            });
          } else {
            // Create new address
            return tx.address.create({
              data: {
                street: address.street,
                city: address.city || '',
                postcode: address.postcode || '',
                country: 'Switzerland',
                order: index,
                latitude: address.latitude,
                longitude: address.longitude,
                routeId: id
              }
            });
          }
        });

        await Promise.all(addressPromises);
      }

      // Return the updated route with sorted addresses
      return tx.route.findUnique({
        where: { id },
        include: {
          addresses: {
            orderBy: {
              order: 'asc'
            }
          }
        }
      });
    });

    return NextResponse.json(updatedRoute);
  } catch (error) {
    console.error("Rota güncellenirken hata oluştu:", error);
    return NextResponse.json(
      { error: "Rota güncellenirken bir hata oluştu" },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { params } = context;
    const { id } = await params;
    
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: "Oturum bulunamadı" },
        { status: 401 }
      );
    }

    const user = await prisma.user.findFirst({
      where: { email: session.user.email },
    });

    if (!user) {
      return NextResponse.json(
        { error: "Kullanıcı bulunamadı" },
        { status: 401 }
      );
    }

    const route = await prisma.route.findFirst({
      where: {
        id: id,
        userId: user.id
      }
    });

    if (!route) {
      return NextResponse.json(
        { error: "Rota bulunamadı veya silme yetkiniz yok" },
        { status: 404 }
      );
    }

    await prisma.route.delete({
      where: {
        id: id
      }
    });

    return NextResponse.json({ message: "Rota başarıyla silindi" });
  } catch (error) {
    console.error("Rota silinirken hata oluştu:", error);
    return NextResponse.json(
      { error: "Rota silinirken bir hata oluştu" },
      { status: 500 }
    );
  }
} 