<?php

namespace apexl\Io\modules\user\entities;

use apexl\entityCore\enums\Casts;
use apexl\entityCore\helpers\Condition;
use apexl\entityCore\traits\hasCasts;
use apexl\Io\includes\Entity;
use apexl\Io\modules\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 TABLE = 'user_meta';

    public function __construct($table = '', $primaryKey = 'id', $extends = null)
    {
        parent::__construct(self::TABLE);
    }

    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,
        ];
    }
}
