<?php

namespace objects;

use classes\db;
use classes\object_property;
use classes\selfserve_schema_bootstrap;
use Exception;
use traits\db_object_t;

class selfserve_machine_types_o extends db
{
    use db_object_t;

    public object_property $name;
    public object_property $description;
    public object_property $created_at;
    public object_property $updated_at;
    public object_property $deleted_at;

    public function structure(): void
    {
        selfserve_schema_bootstrap::ensureTables();
        $this->setTable('selfserve_machine_types');
    }

    public function add(string $name, ?string $description = null): self
    {
        global $db;
        $name = $db->escape_string($name);
        $description = $description === null ? null : $db->escape_string($description);

        $this->id = self::add_object([
            'name' => $name,
            'description' => $description,
        ]);
        $this->getObjectProperties();
        $this->objectChanged();

        return $this;
    }

    public function getObjectProperties(): void
    {
        $this->name = new object_property($this->table, $this->id, 'name', 'string', false);
        $this->description = new object_property($this->table, $this->id, 'description', 'string', false);
        $this->created_at = new object_property($this->table, $this->id, 'created_at', 'timestamp', false);
        $this->updated_at = new object_property($this->table, $this->id, 'updated_at', 'timestamp', false);
        $this->deleted_at = new object_property($this->table, $this->id, 'deleted_at', 'timestamp', false);
    }

    public function objectChanged(): void
    {
        // No dedicated cache invalidation yet.
    }

    public function asArray(): array
    {
        return [
            'id' => (int)$this->id,
            'name' => (string)$this->name->value(),
            'description' => $this->description->value() === null ? null : (string)$this->description->value(),
            'created_at' => (string)$this->created_at->value(),
            'updated_at' => $this->updated_at->value() === null ? null : (string)$this->updated_at->value(),
        ];
    }
}
