<?php

namespace App\Helpers;

class Validator
{
    private array $errors = [];

    public function required(string $field, $value): self
    {
        if (empty(trim((string)$value))) {
            $this->errors[$field] = "$field is required";
        }
        return $this;
    }

    public function min(string $field, $value, int $min): self
    {
        if (strlen((string)$value) < $min) {
            $this->errors[$field] = "$field must be at least $min characters";
        }
        return $this;
    }

    public function max(string $field, $value, int $max): self
    {
        if (strlen((string)$value) > $max) {
            $this->errors[$field] = "$field must be at most $max characters";
        }
        return $this;
    }

    public function email(string $field, $value): self
    {
        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
            $this->errors[$field] = "$field must be a valid email";
        }
        return $this;
    }

    public function passes(): bool
    {
        return empty($this->errors);
    }

    public function errors(): array
    {
        return $this->errors;
    }

    public function firstError(): string
    {
        return reset($this->errors) ?: '';
    }
}
