<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Controller;

use OCA\Mitgliederverwaltung\Service\InventoryReportService;
use OCP\AppFramework\ApiController;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
use OCP\AppFramework\Http\JSONResponse;
use OCP\IRequest;
use Psr\Log\LoggerInterface;

/**
 * REST API controller for inventory reports.
 *
 * Part of Issue #165 (Inventory Tracking).
 */
class InventoryReportController extends ApiController {

    private InventoryReportService $reportService;
    private LoggerInterface $logger;

    public function __construct(
        string $appName,
        IRequest $request,
        InventoryReportService $reportService,
        LoggerInterface $logger
    ) {
        parent::__construct($appName, $request);
        $this->reportService = $reportService;
        $this->logger = $logger;
    }

    /**
     * Get condition report data.
     *
     * GET /api/v1/inventory/reports/condition
     */
    #[NoCSRFRequired]
    public function condition(): JSONResponse {
        try {
            $report = $this->reportService->generateConditionReport();
            $report['title'] = 'Materialzustand';
            return new JSONResponse($report);
        } catch (\Exception $e) {
            $this->logger->error('Failed to generate condition report', ['exception' => $e, 'app' => 'mitgliederverwaltung']);
            return new JSONResponse(['error' => 'Internal server error'], Http::STATUS_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * Get sales report data.
     *
     * GET /api/v1/inventory/reports/sales?dateFrom=2026-01-01&dateTo=2026-03-31
     */
    #[NoCSRFRequired]
    public function sales(): JSONResponse {
        try {
            $dateFrom = $this->request->getParam('dateFrom');
            $dateTo = $this->request->getParam('dateTo');
            $report = $this->reportService->generateSalesReport($dateFrom, $dateTo);
            return new JSONResponse($report);
        } catch (\Exception $e) {
            $this->logger->error('Failed to generate sales report', ['exception' => $e, 'app' => 'mitgliederverwaltung']);
            return new JSONResponse(['error' => 'Internal server error'], Http::STATUS_INTERNAL_SERVER_ERROR);
        }
    }
}
