<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreImportWorkbookRequest;
use App\Models\ImportBatch;
use App\Services\InventoryImportService;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;

class ImportController extends Controller
{
    public function index(): View
    {
        return view('imports.index', [
            'batches' => ImportBatch::query()->latest()->paginate(10),
        ]);
    }

    public function store(StoreImportWorkbookRequest $request, InventoryImportService $importService): RedirectResponse
    {
        $batch = $importService->createBatchFromUpload(
            $request->file('workbook'),
            $request->user(),
            $request->validated('notes')
        );

        return redirect()->route('imports.show', $batch)->with('status', 'File Excel berhasil diunggah dan diparsing.');
    }

    public function show(ImportBatch $import): View
    {
        return view('imports.show', [
            'batch' => $import->load([
                'rows' => fn ($query) => $query->latest('row_number'),
            ]),
        ]);
    }

    public function finalize(ImportBatch $import, InventoryImportService $importService): RedirectResponse
    {
        $importService->finalizeReadyRows($import);

        return redirect()->route('imports.show', $import)->with('status', 'Row siap import berhasil dipindahkan ke data utama.');
    }
}
