<?php

namespace Apexl\Io\User\Entities;

use Apexl\Io\Entity;
use Apexl\Io\Enums\Casts;
use Apexl\Io\Helpers\Condition;
use Apexl\Io\Traits\HasCasts;
use Apexl\Io\User\Collections\UserMetaCollection;
use DateTimeImmutable;

/**
 * @property ?int $id
 * @property UserEntity $user
 * @property string $meta_key
 * @property mixed $meta_value
 * @property ?DateTimeImmutable $created
 * @property ?UserEntity $created_by
 * @property ?DateTimeImmutable $modified
 * @property ?UserEntity $modified_by
 */
class UserMetaEntity extends Entity
{
    use HasCasts {
        HasCasts::casts as traitCasts;
    }

    final public const string TABLE = 'user_meta';

    public static function forUser(int|UserEntity $user): UserMetaCollection
    {
        if ($user instanceof UserEntity) {
            $user = $user->id;
        }

        return UserMetaCollection::createFromArray((new self())->loadMultiple([
            Condition::equals('user', $user),
        ]));
    }

    public static function ofKey(string $key): UserMetaCollection
    {
        return UserMetaCollection::createFromArray((new self())->loadMultiple([
            Condition::equals('meta_key', $key),
        ]));
    }

    public static function forUserOfKey(int|UserEntity $user, string $key): ?UserMetaEntity
    {
        if ($user instanceof UserEntity) {
            $user = $user->id;
        }

        return UserMetaCollection::createFromArray((new self())->loadMultiple([
            Condition::equals('user', $user),
            Condition::equals('meta_key', $key),
        ]))->first();
    }

    public function casts(): array
    {
        return [
            ...$this->traitCasts(),
            'user' => UserEntity::class,
            'meta_value' => Casts::SERIALIZE,
        ];
    }
}
