<?php

namespace Containers\Dto;

readonly class ContainerDto
{
    /**
     * @param ContainerPortDto[] $ports
     */
    public function __construct(
        public string  $hostkey,
        public string  $owner,
        public string  $id,
        public ?string $name,
        public ?string $image,
        public ?string $image_id,
        public ?string $command,
        public ?string $state,
        public array   $ports,
        public ?string $engine,
        public ?string $created_at,
        public ?string $started_at,
        public ?string $finished_at,
        public ?string $collected_at,
        public mixed   $details,
    ) {
    }

    public static function fromRow(array $row): self
    {
        $portsRaw = is_string($row['ports'] ?? null) ? json_decode($row['ports'], true) : ($row['ports'] ?? []);
        $ports = is_array($portsRaw) ? array_map(fn ($p) => ContainerPortDto::fromArray($p), $portsRaw) : [];

        $details = is_string($row['details'] ?? null) ? json_decode($row['details'], true) : ($row['details'] ?? null);

        return new self(
            hostkey: (string) ($row['hostkey'] ?? ''),
            owner: (string) ($row['owner'] ?? ''),
            id: (string) ($row['id'] ?? ''),
            name: $row['name'] ?? null,
            image: $row['image'] ?? null,
            image_id: $row['image_id'] ?? null,
            command: $row['command'] ?? null,
            state: $row['state'] ?? null,
            ports: $ports,
            engine: $row['engine'] ?? null,
            created_at: $row['created_at'] ?? null,
            started_at: $row['started_at'] ?? null,
            finished_at: $row['finished_at'] ?? null,
            collected_at: $row['collected_at'] ?? null,
            details: $details,
        );
    }

    public function toArray(): array
    {
        return [
            'hostkey' => $this->hostkey,
            'owner' => $this->owner,
            'id' => $this->id,
            'name' => $this->name,
            'image' => $this->image,
            'image_id' => $this->image_id,
            'command' => $this->command,
            'state' => $this->state,
            'ports' => array_map(fn (ContainerPortDto $p) => $p->toArray(), $this->ports),
            'engine' => $this->engine,
            'created_at' => $this->created_at,
            'started_at' => $this->started_at,
            'finished_at' => $this->finished_at,
            'collected_at' => $this->collected_at,
            'details' => $this->details,
        ];
    }
}
