<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class ImportAdt1CsvRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create', \App\Models\Compliances\Adt1Compliance::class);
    }

    public function rules(): array
    {
        return [
            'csv_file' => [
                'required',
                'file',
                'mimes:csv,txt',
                function ($attribute, $value, $fail) {
                    $handle = fopen($value->getRealPath(), 'r');
                    $lines = 0;
                    // Strict limit: Header + 500 rows = 501 lines max
                    $maxLines = 501;

                    while (!feof($handle)) {
                        $line = fgets($handle);
                        if ($line !== false && trim($line) !== '') {
                            $lines++;
                        }
                        if ($lines > $maxLines) {
                            $fail('The CSV file cannot contain more than 500 data rows.');
                            break;
                        }
                    }
                    fclose($handle);
                },
            ],
            'financial_session_id' => 'required|exists:financial_sessions,id',
        ];
    }
}
