<?php

declare(strict_types=1);

namespace apexl\Io\dto;

use apexl\dto\Dto;
use apexl\Vault\enums\SortDirection;

final readonly class LoaderSort extends Dto
{
    public function __construct(
        public string $field,
        public SortDirection $direction = SortDirection::ASC,
    ) {}

    public static function createFromString(string $sort): LoaderSort
    {
        return new self(
            field: $sort,
            direction: SortDirection::ASC,
        );
    }

    public static function createFromArray(array $sort): LoaderSort
    {
        [$field, $direction] = array_pad($sort, 2, null);

        $direction = $direction ?? SortDirection::ASC;

        return new self(
            field: $field,
            direction: $direction,
        );
    }

    public function toSql(): string
    {
        return sprintf('%s %s', $this->field, $this->direction->name);
    }
}
