<?php

declare(strict_types=1);

namespace CloudXM\NFe\DTOs;

/**
 * Lifecycle Data DTO
 * 
 * Represents invoice lifecycle timestamps (NEW in v2 API)
 */
class LifecycleData
{
    public function __construct(
        public ?string $created_at = null,
        public ?string $issued_at = null,
        public ?string $cancelled_at = null,
        public ?string $scheduled_for = null,
        public ?string $scheduled_for_local = null,
        public ?string $scheduled_timezone = null
    ) {}

    /**
     * Create from API response array
     */
    public static function fromArray(array $data): self
    {
        return new self(
            created_at: $data['created_at'] ?? null,
            issued_at: $data['issued_at'] ?? null,
            cancelled_at: $data['cancelled_at'] ?? null,
            scheduled_for: $data['scheduled_for'] ?? null,
            scheduled_for_local: $data['scheduled_for_local'] ?? null,
            scheduled_timezone: $data['scheduled_timezone'] ?? null
        );
    }

    /**
     * Validate lifecycle data
     * 
     * @return array Empty array if valid, array of errors if invalid
     */
    public function validate(): array
    {
        $errors = [];

        // Validate timestamp formats if provided
        if ($this->created_at !== null && !$this->isValidTimestamp($this->created_at)) {
            $errors['created_at'] = 'Invalid timestamp format';
        }

        if ($this->issued_at !== null && !$this->isValidTimestamp($this->issued_at)) {
            $errors['issued_at'] = 'Invalid timestamp format';
        }

        if ($this->cancelled_at !== null && !$this->isValidTimestamp($this->cancelled_at)) {
            $errors['cancelled_at'] = 'Invalid timestamp format';
        }

        return $errors;
    }

    /**
     * Check if string is valid ISO 8601 timestamp
     */
    private function isValidTimestamp(string $timestamp): bool
    {
        return strtotime($timestamp) !== false;
    }
}
