<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\NotificationLog;
use App\Models\RateImportLog;
use App\Services\RateImportService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use Throwable;

class RateImportController extends Controller
{
    public function index(): View
    {
        return view('admin.rate-imports.index', [
            'imports' => RateImportLog::query()->with('triggeredBy')->latest()->paginate(12),
            'notifications' => NotificationLog::query()->with('booking')->latest()->limit(20)->get(),
        ]);
    }

    public function run(RateImportService $rateImportService): RedirectResponse
    {
        @set_time_limit(900);
        @ini_set('max_execution_time', '900');

        try {
            $log = $rateImportService->importGuestCalendar('manual', auth()->id());

            $flashType = $log->status === 'success' ? 'success' : 'warning';

            return back()->with($flashType, 'Импорт тарифов завершён: '.$log->date_from.' — '.$log->date_to.'. Статус: '.$log->status.'. Записей: '.$log->rows_written.'.');
        } catch (Throwable $e) {
            return back()->with('error', 'Импорт тарифов не завершился: '.$e->getMessage());
        }
    }
}
