<?php

namespace Velis\Dto\Casters;

use Attribute;
use DateTime;
use Velis\App;
use Velis\Dto\Exceptions\ValidationException;

/**
 * Converts DateTime object to string, using a given format.
 * @author Szymon Janaczek <szymon.janaczek@velistech.com>
 */
#[Attribute]
class CastDateTime implements Castable
{
    public function __construct(private string $format = 'Y-m-d H:i:s')
    {
    }

    /**
     * @throws Exception
     */
    public function get($value, $data = null): ?string
    {
        if (is_null($value)) {
            return null;
        }

        if (is_string($value) && strtotime($value) === false) {
            throw new ValidationException("Invalid date format: $value");
        }

        if (is_string($value)) {
            $value = new DateTime($value);
        }

        return $value
            ->setTimezone(App::getTimezone())
            ->format($this->format);
    }
}
