<?php

namespace App\Http\Controllers\Admin;

use App\Models\Company;
use App\Services\InventoryReportService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class InventoryReportController extends AdminController
{
    public function __construct(
        private readonly InventoryReportService $reportService,
    ) {}

    public function index(Request $request, string $report)
    {
        $config = $this->config($report);
        $company = Company::findOrFail($this->companyId());
        [$dateFrom, $dateTo] = $this->dateRange($request);

        return view('admin.reports.inventory', [
            'company' => $company,
            'reportKey' => $report,
            'config' => $config,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'activeReport' => $report,
            'includeServices' => $request->boolean('include_services'),
        ]);
    }

    public function export(Request $request, string $report)
    {
        $config = $this->config($report);
        $validated = $request->validate([
            'date_from' => ['required', 'date'],
            'date_to' => ['required', 'date', 'after_or_equal:date_from'],
            'include_services' => ['nullable', 'boolean'],
        ]);

        $built = $this->reportService->build(
            $this->companyId(),
            $report,
            $validated['date_from'],
            $validated['date_to'],
            ['include_services' => $request->boolean('include_services')],
        );

        $slug = Str::slug($built['company']->name) ?: 'company';
        $filename = now()->format('Y-m-d')."_{$config['filename_prefix']}_{$slug}.xls";

        return $this->reportService->download($built, $filename);
    }

    /**
     * @return array<string, mixed>
     */
    private function config(string $report): array
    {
        $config = config("reports.inventory.{$report}");
        if (! $config) {
            abort(404);
        }

        return $config;
    }

    /**
     * @return array{0: string, 1: string}
     */
    private function dateRange(Request $request): array
    {
        $dateFrom = $request->query('date_from', now()->subMonth()->format('Y-m-d'));
        $dateTo = $request->query('date_to', now()->format('Y-m-d'));

        return [$dateFrom, $dateTo];
    }
}
