<?php
/**
 * Repository Class
 *
 * @version     1.0.$Revision:$
 * @version     SVN: $Id:$
 * @version     STUB: 2.3.0
 * @generated   2025-06-15 00:00:00
 * @package     bplan-base/globals
 * @subpackage  Repositories
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 * @copyright   Copyright (C) 2025, 2026 bplan-solutions GmbH & Co. KG <https://www.bplan-solutions.de/>
 * /Δ\
 */

namespace BplanBase\Globals\Repositories;


use BplanBase\Globals\Foundation\Repositories\BaseRepository;
use BplanBase\Globals\Helpers\EloquentHelper;
use BplanBase\Globals\Models\EntityType;
use BplanBase\Globals\ValueObjects\PaginateArgs;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Str;


/**
 * Repository Class
 *
 * @version     4.0.0 / 2025-06-17
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
class EntityTypeRepository extends BaseRepository
{


/* +++ TRAITS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ CLASS CONSTANTS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ OBJECT MEMBERS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ CLASS MEMBERS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++++ */


    /**
     * @var     string
     */
    protected static $_modelClass = EntityType::class;


/* +++ OBJECT METHODS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ CLASS METHODS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++++ */


    /**
     * Returns a collection of models
     *
     * @param       bool $ignoreCache
     *              Controls the use of the method cache when determining the result.
     *              If TRUE is passed, a database access is carried out even if the
     *              method cache already contains a suitable entry. The storage of
     *              a value in the method cache is not affected by this parameter.
     *
     * @param       array|string|null $orderBy
     *              For more details @see BplanBase\Globals\Helpers\QueryHelper::applyOrderBy().
     *
     * @param       array|bool|int $paginate
     *              Can be either the number of elements, TRUE or an array. If
     *              TRUE is passed, the default number from the configuration is
     *              used. If an array is passed, then all known arguments for
     *              paginate() (columns, page, pageName, perPage, total) can be
     *              specified in it (all optional).
     *              @see https://api.laravel.com/docs/12.x/Illuminate/Database/Eloquent/Builder.html#method_paginate
     *
     * @param       Builder|null $Query
     *
     * @param       bool $withInactive
     *              By default, only the active data records are returned. By
     *              setting this parameter to TRUE, the inactive data records can
     *              also be included.
     *
     * @param       bool $withInternal
     *              By default, records marked as internal are excluded. Setting
     *              this parameter to TRUE allows internal records to be included
     *              as well.
     *
     * @return      Collection|LengthAwarePaginator<EntityType>
     *
     * @version     3.1.0 / 2025-06-15
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public static function getAll(bool $ignoreCache = false, array|string|null $orderBy = null, array|bool|int $paginate = false, Builder|null $Query = null, bool $withInactive = false, bool $withInternal = false): Collection|LengthAwarePaginator
    {
        static $cache = [];

        $cacheKey = md5(json_encode(func_get_args()));

        if ($paginate !== false) {
            $ignoreCache = true;
        }
        if ($ignoreCache === false && isset($cache[$cacheKey])) {
            return $cache[$cacheKey];
        }
        $Query = self::_resolveQuery($Query);

        if ($withInactive === false) {
            $Query->active();
        }
        if ($withInternal === false) {
            $Query->noInternal();
        }
        $Query->ordered($orderBy);

        if ($paginate === false) {
            return $cache[$cacheKey] = $Query->get();
        }
        $PaginateArgs = PaginateArgs::from($paginate);

        return $Query->paginate(...$PaginateArgs->toArray());

    } // getAll()


    /**
     * Returns the model instance for the given ID
     *
     * @param       int|string $id
     *
     * @param       bool $ignoreCache
     *              Controls the use of the method cache when determining the result.
     *              If TRUE is passed, a database access is carried out even if the method cache
     *              already contains a suitable entry. The storage of a value in the method cache
     *              is not affected by this parameter.
     *
     * @param       bool $returnOrFail
     *              Controls the return of the method.
     *              If no suitable entry can be found in the database, either NULL is returned (TRUE)
     *              or an exception is thrown (FALSE). This allows the result of the method call to
     *              be used directly in the Api controller.
     *
     * @throws      Illuminate\Database\Eloquent\ModelNotFoundException
     *
     * @return      EntityType|null
     *
     * @version     2.0.0 / 2025-06-04
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public static function getById(int|string $id, bool $ignoreCache = false, bool $returnOrFail = true): EntityType|null
    {
        static $cache = [];

        $cacheKey = md5(serialize(func_get_args()));

        if ($ignoreCache === false && isset($cache[$cacheKey])) {
            return $cache[$cacheKey];
        }
        $Query = static::$_modelClass::query();

        if ($returnOrFail === true) {
            return $cache[$cacheKey] = $Query->find($id);
        }
        return $cache[$cacheKey] = $Query->findOrFail($id);

    } // getById()


    /**
     * Returns the model instance for the given UUID
     *
     * @param       string $uuid
     *
     * @param       bool $ignoreCache
     *              Controls the use of the method cache when determining the result.
     *              If TRUE is passed, a database access is carried out even if the method cache
     *              already contains a suitable entry. The storage of a value in the method cache
     *              is not affected by this parameter.
     *
     * @param       bool $returnOrFail
     *              Controls the return of the method.
     *              If no suitable entry can be found in the database, either NULL is returned (TRUE)
     *              or an exception is thrown (FALSE). This allows the result of the method call to
     *              be used directly in the Api controller.
     *
     * @throws      Illuminate\Database\Eloquent\ModelNotFoundException
     *
     * @return      EntityType|null
     *
     * @version     1.0.0 / 2025-06-04
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public static function getByUuid(int|string $uuid, bool $ignoreCache = false, bool $returnOrFail = true): EntityType|null
    {
        static $cache = [];

        $cacheKey = md5(serialize(func_get_args()));

        if ($ignoreCache === false && isset($cache[$cacheKey])) {
            return $cache[$cacheKey];
        }
        $Query = static::$_modelClass::where('uuid', '=', $uuid);

        if ($returnOrFail === true) {
            return $cache[$cacheKey] = $Query->first();
        }
        return $cache[$cacheKey] = $Query->firstOrFail();

    } // getByUuid()


    /**
     * Returns the fully qualified class name of a Livewire component class
     *
     * @param       int|string|EntityType $entityType
     *
     * @param       null|string $className
     *              Should be "Create" or "Edit". If NULL is passed, only the namespace for the
     *              class is returned.
     *
     * @param       bool $ignoreCache
     *              Controls the use of the method cache when determining the result.
     *              If TRUE is passed, a database access is carried out even if the method cache
     *              already contains a suitable entry. The storage of a value in the method cache
     *              is not affected by this parameter.
     *
     * @return      string
     *
     * @version     1.0.0 / 2025-06-17
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public static function getLivewireComponentClass(int|string|Model $entityType, null|string $className = null, bool $ignoreCache = false): string
    {
        static $cache = [];

        $cacheKey = md5(serialize(func_get_args()));

        if ($ignoreCache === false && isset($cache[$cacheKey])) {
            return $cache[$cacheKey];
        }
        $EntityType = self::_resolveModel($entityType);

        $EntityTypeModel = EntityTypeModelRepository::getById($EntityType->model_id, ignoreCache: $ignoreCache);

        $baseNamespace = str_replace(
            ['Models', $EntityTypeModel->identifier],
            ['Livewire', ''],
            $EntityTypeModel->fully_qualified_class_name
        );
        $namespace = $baseNamespace.Str::plural($EntityTypeModel->identifier).'\\Modals';

        if ($className === null) {
            return $cache[$cacheKey] = $namespace;
        }
        return $cache[$cacheKey] = $namespace.'\\'.Str::studly($className);

    } // getLivewireComponentClass()


    /**
     * Returns an array with ID => label based on language code and fallback
     *
     * @param       string|null $locale
     *              If not given config('app.locale') is used.
     *
     * @param       bool $ignoreCache
     *              Controls the use of the method cache when determining the result.
     *              If TRUE is passed, a database access is carried out even if the method cache
     *              already contains a suitable entry. The storage of a value in the method cache
     *              is not affected by this parameter.
     *
     * @param       bool $withInactive
     *              By default, only the active data records are returned. By
     *              setting this parameter to TRUE, the inactive data records can
     *              also be read out.
     *
     * @return      array<string, string>
     *
     * @version     1.0.0 / 2025-05-29
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public static function getLocalizedList(string|null $locale = null, bool $ignoreCache = false, bool $withInactive = false): array
    {
        if ($locale === null) {
            $locale = config('app.locale');
        }
        static $cache = [];

        $cacheKey = md5(serialize(func_get_args()));

        if ($ignoreCache === false && isset($cache[$cacheKey])) {
            return $cache[$cacheKey];
        }
        $Query = static::$_modelClass::query();

        if ($withInactive === false) {
            $Query->active();
        }
        return $cache[$cacheKey] = EloquentHelper::getLocalizedCollection($Query, $locale, 'labels', fallbackAttribute: 'identifier')
            ->sort()
            ->toArray();

    } // getLocalizedList()


} // class EntityTypeRepository extends BaseRepository {}
