<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AgencyManagementReport;
use App\Services\Operations\AgencyManagementReportService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Illuminate\View\View;

class AgencyManagementReportController extends Controller
{
    public function __construct(protected AgencyManagementReportService $reports)
    {
    }

    public function index(Request $request): View
    {
        $data = $this->reports->dashboard($request->only(['period_type', 'date_from', 'date_to']));

        return view('admin.management-reports.index', compact('data'));
    }

    public function generate(Request $request): RedirectResponse
    {
        $payload = $request->validate([
            'period_type' => ['nullable', 'in:daily,weekly,monthly,custom'],
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date', 'after_or_equal:date_from'],
        ]);

        $report = $this->reports->generate($payload);

        if ($report->status === 'failed') {
            return back()->with('error', 'Ajans yönetim raporu oluşturulamadı: '.$report->error_message);
        }

        return redirect()
            ->route('admin.management-reports.show', $report)
            ->with('success', 'Ajans yönetim raporu oluşturuldu.');
    }

    public function show(AgencyManagementReport $managementReport): View
    {
        return view('admin.management-reports.show', ['report' => $managementReport]);
    }

    public function regenerate(AgencyManagementReport $managementReport): RedirectResponse
    {
        $this->reports->regenerate($managementReport);

        return back()->with('success', 'Ajans yönetim raporu yeniden oluşturuldu.');
    }

    public function download(AgencyManagementReport $managementReport, string $type): BinaryFileResponse|StreamedResponse|RedirectResponse
    {
        $path = match ($type) {
            'html' => $managementReport->html_path,
            'csv' => $managementReport->csv_path,
            default => null,
        };

        if (! $path || ! Storage::disk('public')->exists($path)) {
            return back()->with('error', 'İstenen dosya bulunamadı.');
        }

        return Storage::disk('public')->download($path);
    }
}
