<?php
declare(strict_types=1);

namespace FreshCloud\Mail\Compose;

enum ComposeStatus
{
    case Sent;
    case Queued;
    case Failed;
    case DraftSaved;

    public function toWire(): string
    {
        return match ($this) {
            self::Sent => 'sent',
            self::Queued => 'queued',
            self::Failed => 'failed',
            self::DraftSaved => 'draft_saved',
        };
    }

    public static function fromWire(string $value): self
    {
        return match ($value) {
            'sent' => self::Sent,
            'queued' => self::Queued,
            'failed' => self::Failed,
            'draft_saved' => self::DraftSaved,
            default => throw new \ValueError("Invalid ComposeStatus wire value: {$value}"),
        };
    }
}


final readonly class ComposeResult
{
    public function __construct(
        public ComposeStatus $status,
        public ?string $messageId,
        public ?string $draftId,
        public ?\DateTimeImmutable $sentAt,
        public ?string $error
    ) {}

    public static function fromArray(array $data): self
    {
        $statusStr = $data['status'] ?? 'failed';
        $status = \FreshCloud\Mail\Compose\ComposeStatus::fromWire($statusStr);
        
        $sentAt = null;
        if (!empty($data['sent_at'])) {
            try {
                $sentAt = new \DateTimeImmutable((string) $data['sent_at']);
            } catch (\Throwable $e) {
                $sentAt = null;
            }
        }
        
        return new self(
            status: $status,
            messageId: $data['message_id'] ?? null,
            draftId: $data['draft_id'] ?? null,
            sentAt: $sentAt,
            error: $data['error'] ?? null,
        );
    }

    public function toArray(): array
    {
        return [
            'status' => $this->status->toWire(),
            'message_id' => $this->messageId,
            'draft_id' => $this->draftId,
            'sent_at' => $this->sentAt?->format(\DateTimeInterface::ATOM),
            'error' => $this->error,
        ];
    }
}
