import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { db } from '@/lib/db';
import { z } from 'zod';

interface RouteContext {
  params: Promise<{ id: string }>;
}

// Validation schema for stock adjustment
const stockAdjustmentSchema = z.object({
  adjustment: z.number().int('Adjustment must be an integer'),
  reason: z.string().min(1, 'Reason is required').max(500),
});

// POST /api/products/[id]/stock - Adjust product stock
export async function POST(
  request: NextRequest,
  context: RouteContext
) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    // Check if user has appropriate role
    const allowedRoles = ['SUPER_ADMIN', 'ORG_ADMIN', 'SITE_ADMIN', 'RECEPTIONIST'];
    if (!allowedRoles.includes(session.user.role)) {
      return NextResponse.json(
        { error: 'Forbidden: Insufficient permissions' },
        { status: 403 }
      );
    }

    const { id } = await context.params;

    // Verify product exists and belongs to user's organization
    const existingProduct = await db.product.findFirst({
      where: {
        id,
        organizationId: session.user.organizationId,
      },
    });

    if (!existingProduct) {
      return NextResponse.json(
        { error: 'Product not found' },
        { status: 404 }
      );
    }

    if (!existingProduct.isActive) {
      return NextResponse.json(
        { error: 'Cannot adjust stock for an inactive product' },
        { status: 400 }
      );
    }

    if (!existingProduct.trackStock) {
      return NextResponse.json(
        { error: 'Stock tracking is disabled for this product' },
        { status: 400 }
      );
    }

    const body = await request.json();

    // Validate input with Zod schema
    const validationResult = stockAdjustmentSchema.safeParse(body);
    if (!validationResult.success) {
      return NextResponse.json(
        {
          error: 'Invalid stock adjustment data',
          details: validationResult.error.flatten().fieldErrors,
        },
        { status: 400 }
      );
    }

    const { adjustment, reason } = validationResult.data;

    // Calculate new stock
    const newStock = existingProduct.stock + adjustment;

    // Validate stock doesn't go below 0
    if (newStock < 0) {
      return NextResponse.json(
        {
          error: 'Stock cannot go below 0',
          details: {
            currentStock: existingProduct.stock,
            requestedAdjustment: adjustment,
            resultingStock: newStock,
          },
        },
        { status: 400 }
      );
    }

    // Update the product stock
    const product = await db.product.update({
      where: { id },
      data: {
        stock: newStock,
      },
      include: {
        category: {
          select: {
            id: true,
            name: true,
            description: true,
          },
        },
      },
    });

    // Log the stock adjustment (using console for now; could be a separate StockMovement table)
    console.log('Stock adjustment:', {
      productId: id,
      productName: product.name,
      previousStock: existingProduct.stock,
      adjustment,
      newStock,
      reason,
      adjustedBy: session.user.id,
      adjustedAt: new Date().toISOString(),
    });

    // Add lowStock indicator
    const productWithLowStock = {
      ...product,
      previousStock: existingProduct.stock,
      adjustment,
      reason,
      lowStock: product.trackStock && product.stock < product.minStock,
    };

    return NextResponse.json(productWithLowStock);
  } catch (error) {
    console.error('Error adjusting product stock:', error);
    return NextResponse.json(
      { error: 'Failed to adjust product stock' },
      { status: 500 }
    );
  }
}
