<?php

namespace App\Imports;

use App\Models\ImportBatch;
use App\Models\VisitRawStaging;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;

class VisitsStagingImport implements ToCollection, WithHeadingRow, WithValidation, WithChunkReading
{
    public function __construct(
        protected ImportBatch $importBatch
    ) {}

    public function chunkSize(): int
    {
        return 500;
    }

    public function collection(Collection $rows): void
    {
        foreach ($rows as $index => $row) {
            $rowIndex = $index + 2; // 1-based, +1 for heading row
            $rawData = $row->toArray();
            $rawData = array_filter($rawData, fn ($v) => $v !== null && $v !== '');

            VisitRawStaging::create([
                'import_batch_id' => $this->importBatch->id,
                'row_index' => $rowIndex,
                'raw_data' => $rawData,
                'validation_status' => 'pending',
            ]);
        }
    }

    public function rules(): array
    {
        return [];
    }
}
