<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\DataImportBatch;
use App\Services\DataImportService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Illuminate\View\View;

class DataImportController extends Controller
{
    public function index(): View
    {
        return view('tenant.data-imports.index', [
            'types' => DataImportService::TYPES,
            'batches' => DataImportBatch::with('user')->latest()->paginate(10),
        ]);
    }

    public function store(Request $request, DataImportService $imports): RedirectResponse
    {
        $validated = $request->validate([
            'import_type' => ['required', 'in:'.implode(',', array_keys(DataImportService::TYPES))],
            'file' => ['required', 'file', 'mimes:csv,txt', 'max:10240'],
        ]);

        $batch = $imports->import(
            $request->user()->tenant,
            $request->user(),
            $validated['import_type'],
            $validated['file'],
        );

        return back()->with($batch->failed_rows > 0 ? 'warning' : 'status', 'Import finished: '.$batch->successful_rows.' row(s) imported, '.$batch->failed_rows.' failed.');
    }

    public function template(string $type, DataImportService $imports): StreamedResponse
    {
        abort_unless(isset(DataImportService::TYPES[$type]), 404);

        return response()->streamDownload(function () use ($imports, $type): void {
            $handle = fopen('php://output', 'wb');
            foreach ($imports->template($type) as $row) {
                fputcsv($handle, $row);
            }
            fclose($handle);
        }, $type.'-import-template.csv', ['Content-Type' => 'text/csv']);
    }
}
