import type { Request, Response } from 'express';
import { StockSpoilageService } from '../services/StockSpoilageService.js';
import { Prisma } from '../generated/prisma/client.js';

export class StockSpoilageController {
  static async create(req: Request, res: Response): Promise<void> {
    try {
      const { purchaseId, quantity, spoilageDate, reason, remarks } = req.body;

      if (!purchaseId || quantity === undefined || !spoilageDate) {
        res.status(400).json({ error: 'purchaseId, quantity, and spoilageDate are required.' });
        return;
      }

      const spoilage = await StockSpoilageService.createSpoilage({
        purchaseId: BigInt(purchaseId),
        quantity: new Prisma.Decimal(quantity),
        spoilageDate: new Date(spoilageDate),
        reason,
        remarks,
        createdBy: req.user?.id ? BigInt(req.user.id) : undefined,
      } as any);

      // Convert BigInt to string for JSON serialization
      const serialized = JSON.parse(
        JSON.stringify(spoilage, (key, value) =>
          typeof value === 'bigint' ? value.toString() : value
        )
      );

      res.status(201).json(serialized);
    } catch (error: any) {
      console.error('Error creating stock spoilage:', error);
      res.status(400).json({ error: error.message || 'Internal Server Error' });
    }
  }

  static async list(req: Request, res: Response): Promise<void> {
    try {
      const { purchaseId, vegetableId, from, to } = req.query;

      const filters = {
        purchaseId: purchaseId ? BigInt(purchaseId as string) : undefined,
        vegetableId: vegetableId ? BigInt(vegetableId as string) : undefined,
        from: from ? new Date(from as string) : undefined,
        to: to ? new Date(to as string) : undefined,
      };

      const spoilages = await StockSpoilageService.listSpoilages(filters as any);

      const serialized = JSON.parse(
        JSON.stringify(spoilages, (key, value) =>
          typeof value === 'bigint' ? value.toString() : value
        )
      );

      res.status(200).json({ message: "Stock spoilages listed successfully", "result": serialized });
    } catch (error: any) {
      console.error('Error listing stock spoilages:', error);
      res.status(500).json({ error: 'Internal Server Error' });
    }
  }
}
