<?php

namespace App\Repositories\Ecommerce\Product\Brand;

use App\Models\Ecommerce\Product\Brand\Brand;
use Illuminate\Support\Collection;

class BrandRepository
{
    /**
     * Model
     */
    private $model;

    /**
     * Query Builder
     */
    protected $queryBuilder;

    /**
     * Related to nova ?
     */
    private bool $nova;

    /**
     * @param  bool|bool  $nova
     */
    public function __construct(Brand $model, bool $nova = false)
    {
        $this->model = $model;
        $this->nova = $nova;

        $this->queryBuilder = Brand::query();
    }

    /**
     * Related to Nova
     */
    public static function nova(): self
    {
        return new self(model: (new Brand), nova: true);
    }

    /**
     * Channels
     */
    public static function values(): array|Collection
    {
        return Brand::where('is_visible', true)
            ->pluck('name', 'id')
            ->prepend(sprintf('------- %s -------', __('No')), '');
    }

    public function filterBy($resource)
    {
        if (get_class($resource) === config('ecommerce.models.brand')) {
            return [$resource];
        }

        if (in_array(get_class($resource), [
            config('ecommerce.models.brand.collection'),
            config('ecommerce.models.brand.category'),
        ])) {
            return $this->queryBuilder->whereIntegerInRaw(
                column: 'id',
                values: $resource->products()->distinct('brand_id')->pluck('brand_id')
            )->get(['id', 'name']);
        }

        return [];
    }
}
