<?php

namespace App\Models;

use App\Services\Auth0Service;
use App\Traits\UuidPrimaryKey;
use App\Exceptions\ModelNotFoundException;
use App\Exceptions\HasNoPermissionsOnRestaurantException;
use App\Exceptions\CantManageRestaurantsException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Log;

class Usuario extends Model {
    use UuidPrimaryKey, SoftDeletes;

    protected $table = 'usuarios';
    protected $hidden = ['created_at', 'updated_at', 'deleted_at', 'pivot'];
    protected $fillable = ['id', 'auth0_id', 'nombre'];
    protected $appends = ['roles'];

    /**
     * Busca un usuario o envia una excepcion si no se encuentra
     */
    public static function findOrFail($id) {
        if (str_starts_with($id, 'auth0')) $usuario = Usuario::where('auth0_id', urldecode($id))->first();
        else $usuario = Usuario::where('id', $id)->first();

        if(!$usuario) throw new ModelNotFoundException("usuario", $id);

        return $usuario;
    }

    public function isGlobalAdmin() {
        return $this->hasRole('global_admin');
    }

    public function isAdmin() {
        return $this->hasRole('admin');
    }

    public function hasRole($role) {
        return in_array($role, $this->roles);
    }

    public function isOnRestaurante($restaurante) {
        if($this->isGlobalAdmin()) return true;
        return $this->restaurantes()->where('id', $restaurante->id)->count() > 0;
    }

    public function isColega($usuario) {
        return $this->colegas()->contains($usuario);
    }

    public function colegas() {
        if($this->isGlobalAdmin()) return Usuario::all();

        $restaurantes = $this->restaurantes;
        $colegas = collect([]);

        foreach($restaurantes as $restaurant) {
            $colegas = $colegas->merge($restaurant->usuarios);
        }

        return $colegas->unique('id');
    }

    public function restaurantes() {
        return $this->belongsToMany(Restaurante::class, 'usuarios_restaurantes', 'usuario_id', 'restaurante_id');
    }

    public function zonasProduccion() {
        return $this->belongsToMany(ZonaProduccion::class, 'productores', 'usuario_id', 'zona_produccion_id');
    }


    public function getRolesAttribute() {
        $auth0Service = app(Auth0Service::class);
        $auth0User = $auth0Service->getUser($this->auth0_id);
        return $this->attributes['roles'] = array_key_exists('app_metadata', $auth0User) ? $auth0User['app_metadata']['roles'] : [];
    }
}
