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

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

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

      const saleReturn = await SaleReturnService.createSaleReturn(BigInt(saleItemId as string), {
        quantity: new Prisma.Decimal(quantity),
        returnDate: new Date(returnDate),
        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(saleReturn, (key, value) =>
          typeof value === 'bigint' ? value.toString() : value
        )
      );

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

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

      const walkInBool = isWalkIn === 'true' || customerId === 'walkin';

      let parsedCustomerId: bigint | undefined = undefined;
      if (customerId && !walkInBool) {
        try {
          parsedCustomerId = BigInt(customerId as string);
        } catch {
          parsedCustomerId = undefined;
        }
      }

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

      const returns = await SaleReturnService.listSaleReturns(filters as any);

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

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