<?php

namespace App\Services;

use App\Http\Resources\CompanyDefaultPermissionsResource;
use App\Models\CompanyDefaultPermissions;
use App\Models\Permissions;
use App\Models\UserType;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

class CompanyDefaultPermissionsServirce
{
    use HasResponse;

    public function list($withPagination)
    {
        $companyDefaultPermissions = CompanyDefaultPermissions::companyDefaultPermissionsFilters() # Filtrado por el modelo
            ->orderBy('id', 'desc');

        $companyDefaultPermissions = !empty($withPagination)
            ? $companyDefaultPermissions->paginate($withPagination['perPage'], page: $withPagination['page'])
            : $companyDefaultPermissions->get();

        $companyDefaultPermissions = CompanyDefaultPermissionsResource::collection($companyDefaultPermissions->load('userType', 'company'));

        return $this->successResponse('Lectura exitosa.', $companyDefaultPermissions);
    }


    public function update($id, $params)
    {
        DB::beginTransaction();
        try {

            # Verificar que el registro sea válido
            $companyDefaultPermissions = CompanyDefaultPermissions::find($id);
            if (!$companyDefaultPermissions) return $this->errorResponse('El registro es inválido.', 400);

            # Verificar validez de las llaves
            $validate = $this->verifyFK($params['iduser_type'], $params['permissions']);
            if (!$validate->original['status']) return $validate;

            $typeUser = UserType::find($params['iduser_type'])->name;

            $companyDefaultPermissions->update(['permissions' => $params['permissions']]);

            DB::commit();
            return $this->successResponse("Permisos para el rol $typeUser actualizado satisfactoriamente.", $companyDefaultPermissions);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la actualización de los permisos de un rol.', $th->getMessage());
        }
    }

    private function verifyFK($typeUser, $permissions)
    {
        $typeUser = UserType::activeForID($typeUser)->first();
        if (!$typeUser) return $this->errorResponse('El tipo de usuario seleccionado es inválido.', 400);

        $validatePermissions = Permissions::whereIn('id', $permissions)->count();
        if (count($permissions) !=  $validatePermissions) return $this->errorResponse('Selección de permisos inválida.', 400);


        return $this->successResponse('OK');
    }
}
