<?php

namespace App\Support;

use App\Models\FactoryProduct;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;

final class ProductionFormulaAccess
{
    public static function mayViewAll(?User $user): bool
    {
        return $user !== null && $user->hasRole('Master Admin', 'web');
    }

    public static function mayView(?User $user, FactoryProduct $product): bool
    {
        if ($user === null || ! $user->can('production-formulas.view')) {
            return false;
        }

        if (self::mayViewAll($user)) {
            return true;
        }

        return (int) $product->formula_created_by === (int) $user->id;
    }

    public static function mayCreate(?User $user): bool
    {
        return $user !== null && $user->can('production-formulas.create');
    }

    public static function mayUpdate(?User $user, FactoryProduct $product): bool
    {
        if ($user === null || ! $user->can('production-formulas.update')) {
            return false;
        }

        if (self::mayViewAll($user)) {
            return true;
        }

        return (int) $product->formula_created_by === (int) $user->id;
    }

    /**
     * @param  list<int>  $factoryProductIds
     * @return list<int>
     */
    public static function filterVisibleProductIds(?User $user, array $factoryProductIds): array
    {
        $factoryProductIds = array_values(array_unique(array_filter($factoryProductIds)));

        if ($factoryProductIds === [] || $user === null) {
            return [];
        }

        if (self::mayViewAll($user)) {
            return $factoryProductIds;
        }

        return FactoryProduct::query()
            ->whereIn('id', $factoryProductIds)
            ->where('formula_created_by', $user->id)
            ->pluck('id')
            ->map(fn (mixed $id): int => (int) $id)
            ->all();
    }

    /**
     * @param  Builder<FactoryProduct>  $query
     * @return Builder<FactoryProduct>
     */
    public static function applyVisibleFormulaScope(Builder $query, ?User $user): Builder
    {
        if ($user === null) {
            return $query->whereRaw('0 = 1');
        }

        if (self::mayViewAll($user)) {
            return $query;
        }

        return $query->where('formula_created_by', $user->id);
    }
}
