import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { cookies } from 'next/headers';
import { z } from 'zod';
import { validateBody } from '@/lib/api-validation';

export const dynamic = 'force-dynamic';

const addToCartSchema = z.object({
  variantId: z.string().min(1, 'Variant ID is required'),
  quantity: z.number().int().min(1).max(100).default(1),
});

const removeFromCartSchema = z.object({
  itemId: z.string().min(1, 'Item ID is required'),
});

async function getOrCreateCart(sessionId: string) {
  let cart = await prisma.swagCart.findUnique({
    where: { sessionId },
    include: {
      items: {
        include: {
          variant: {
            include: { product: true },
          },
        },
      },
    },
  });

  if (!cart) {
    cart = await prisma.swagCart.create({
      data: {
        sessionId,
        expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days
      },
      include: {
        items: {
          include: {
            variant: {
              include: { product: true },
            },
          },
        },
      },
    });
  }

  return cart;
}

export async function GET(request: NextRequest) {
  try {
    const cookieStore = await cookies();
    let sessionId = cookieStore.get('swag_session')?.value;
    
    if (!sessionId) {
      sessionId = `sess_${Date.now()}_${Math.random().toString(36).slice(2)}`;
    }

    const cart = await getOrCreateCart(sessionId);
    
    const response = NextResponse.json({ cart });
    response.cookies.set('swag_session', sessionId, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 7 * 24 * 60 * 60,
    });
    
    return response;
  } catch (error) {
    console.error('Error fetching cart:', error);
    return NextResponse.json({ error: 'Failed to fetch cart' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const result = await validateBody(request, addToCartSchema);
    if (result.error) return result.error;
    const { variantId } = result.data;
    const quantity = result.data.quantity ?? 1;
    const cookieStore = await cookies();
    let sessionId = cookieStore.get('swag_session')?.value;
    
    if (!sessionId) {
      sessionId = `sess_${Date.now()}_${Math.random().toString(36).slice(2)}`;
    }

    const cart = await getOrCreateCart(sessionId);

    // Check stock
    const variant = await prisma.swagVariant.findUnique({
      where: { id: variantId },
    });

    if (!variant || variant.stock - variant.reserved < quantity) {
      return NextResponse.json({ error: 'Insufficient stock' }, { status: 400 });
    }

    // Update or create cart item
    const existingItem = cart.items.find((i: any) => i.variantId === variantId);
    
    if (existingItem) {
      await prisma.swagCartItem.update({
        where: { id: existingItem.id },
        data: { quantity: existingItem.quantity + quantity },
      });
    } else {
      await prisma.swagCartItem.create({
        data: {
          cartId: cart.id,
          variantId,
          quantity,
        },
      });
    }

    // Reserve stock
    await prisma.swagVariant.update({
      where: { id: variantId },
      data: { reserved: { increment: quantity } },
    });

    const updatedCart = await getOrCreateCart(sessionId);
    
    const response = NextResponse.json({ cart: updatedCart });
    response.cookies.set('swag_session', sessionId, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 7 * 24 * 60 * 60,
    });
    
    return response;
  } catch (error) {
    console.error('Error adding to cart:', error);
    return NextResponse.json({ error: 'Failed to add to cart' }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const result = await validateBody(request, removeFromCartSchema);
    if (result.error) return result.error;
    const { itemId } = result.data;
    const cookieStore = await cookies();
    const sessionId = cookieStore.get('swag_session')?.value;
    
    if (!sessionId) {
      return NextResponse.json({ error: 'No cart found' }, { status: 404 });
    }

    const item = await prisma.swagCartItem.findUnique({
      where: { id: itemId },
      include: { cart: true },
    });

    if (!item || item.cart.sessionId !== sessionId) {
      return NextResponse.json({ error: 'Item not found' }, { status: 404 });
    }

    // Release reserved stock
    await prisma.swagVariant.update({
      where: { id: item.variantId },
      data: { reserved: { decrement: item.quantity } },
    });

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

    const cart = await getOrCreateCart(sessionId);
    return NextResponse.json({ cart });
  } catch (error) {
    console.error('Error removing from cart:', error);
    return NextResponse.json({ error: 'Failed to remove from cart' }, { status: 500 });
  }
}
