<?php

namespace App\Http\Controllers;

use App\Imports\YammaYapEquipmentImport;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Facades\Excel;

class YammaYapEquipmentImportController extends Controller
{
    public function import(Request $request): array
    {
        $request->validate([
            'file' => 'required|file|mimes:csv,txt',
            'delimiter' => 'sometimes|string|max:5',
        ]);

        $this->validateHeaders($request->file('file'));

        $delimiter = $request->input('delimiter', ',');
        $import = new YammaYapEquipmentImport($delimiter);
        Excel::import($import, $request->file('file'));

        return [
            'success' => true,
            'deleted' => $import->deleted,
            'imported' => $import->imported,
            'skipped_rows' => $import->skippedRows,
            'skipped_uuids' => $import->skippedUuids,
        ];
    }

    private function validateHeaders($file): void
    {
        $handle = fopen($file->getPathname(), 'r');
        $headers = fgetcsv($handle);
        fclose($handle);

        if (!$headers) {
            throw ValidationException::withMessages([
                'file' => ['The CSV file is empty or could not be read.'],
            ]);
        }

        $headers = array_map('trim', $headers);
        $missingHeaders = array_diff(
            YammaYapEquipmentImport::REQUIRED_HEADERS,
            $headers
        );

        if (!empty($missingHeaders)) {
            throw ValidationException::withMessages([
                'file' => [
                    'The CSV is missing required headers: '
                    . implode(', ', $missingHeaders),
                ],
            ]);
        }
    }
}
