import { FastifyRequest, FastifyReply } from 'fastify';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

// Get all supply items
export async function getSupplyItems(request: FastifyRequest, reply: FastifyReply) {
    try {
        const items = await prisma.supplyItem.findMany({
            orderBy: [
                { category: 'asc' },
                { name: 'asc' },
            ],
        });

        return reply.send(items);
    } catch (error: any) {
        return reply.status(500).send({ message: error.message });
    }
}

// Get shopping list (items below threshold)
export async function getShoppingList(request: FastifyRequest, reply: FastifyReply) {
    try {
        const items = await prisma.supplyItem.findMany({
            orderBy: [
                { category: 'asc' },
                { name: 'asc' },
            ],
        });

        const shoppingList = items.filter(item => item.quantity <= item.minThreshold);

        return reply.send(shoppingList);
    } catch (error: any) {
        return reply.status(500).send({ message: error.message });
    }
}

// Get single supply item
export async function getSupplyItem(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) {
    try {
        const { id } = request.params;

        const item = await prisma.supplyItem.findUnique({
            where: { id },
        });

        if (!item) {
            return reply.status(404).send({ message: 'Supply item not found' });
        }

        return reply.send(item);
    } catch (error: any) {
        return reply.status(500).send({ message: error.message });
    }
}

// Create supply item
export async function createSupplyItem(
    request: FastifyRequest<{
        Body: {
            name: string;
            category: string;
            quantity?: number;
            minThreshold?: number;
            unit: string;
            location?: string;
            vendor?: string;
            productUrl?: string;
            notes?: string;
        };
    }>,
    reply: FastifyReply
) {
    try {
        const { name, category, quantity, minThreshold, unit, location, vendor, productUrl, notes } = request.body;

        const item = await prisma.supplyItem.create({
            data: {
                name,
                category: category as any,
                quantity: quantity || 0,
                minThreshold: minThreshold || 0,
                unit,
                location,
                vendor,
                productUrl,
                notes,
            },
        });

        return reply.status(201).send(item);
    } catch (error: any) {
        return reply.status(500).send({ message: error.message });
    }
}

// Update supply item
export async function updateSupplyItem(
    request: FastifyRequest<{
        Params: { id: string };
        Body: {
            name?: string;
            category?: string;
            quantity?: number;
            minThreshold?: number;
            unit?: string;
            location?: string;
            vendor?: string;
            productUrl?: string;
            notes?: string;
        };
    }>,
    reply: FastifyReply
) {
    try {
        const { id } = request.params;
        const data = request.body;

        const item = await prisma.supplyItem.update({
            where: { id },
            data: {
                ...data,
                category: data.category as any,
            },
        });

        return reply.send(item);
    } catch (error: any) {
        return reply.status(500).send({ message: error.message });
    }
}

// Delete supply item
export async function deleteSupplyItem(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) {
    try {
        const { id } = request.params;

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

        return reply.status(204).send();
    } catch (error: any) {
        return reply.status(500).send({ message: error.message });
    }
}

// Mark item as ordered
export async function markAsOrdered(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) {
    try {
        const { id } = request.params;

        const item = await prisma.supplyItem.update({
            where: { id },
            data: {
                lastOrdered: new Date(),
            },
        });

        return reply.send(item);
    } catch (error: any) {
        return reply.status(500).send({ message: error.message });
    }
}

// Adjust quantity (add or subtract)
export async function adjustQuantity(
    request: FastifyRequest<{
        Params: { id: string };
        Body: { adjustment: number };
    }>,
    reply: FastifyReply
) {
    try {
        const { id } = request.params;
        const { adjustment } = request.body;

        const item = await prisma.supplyItem.findUnique({ where: { id } });
        if (!item) {
            return reply.status(404).send({ message: 'Supply item not found' });
        }

        const updated = await prisma.supplyItem.update({
            where: { id },
            data: {
                quantity: Math.max(0, item.quantity + adjustment),
            },
        });

        return reply.send(updated);
    } catch (error: any) {
        return reply.status(500).send({ message: error.message });
    }
}
