<?php

namespace App\Services\SM;

use App\Exceptions\CustomException;
use App\Models\User;
use App\Traits\DataTable;
use Exception;

class UserService
{
    /**
     * Create a new class instance.
     */
    use DataTable;
    public function __construct(private User $model)
    {
        //
    }

    public function dataTable()
    {
        return $this->generate($this->model->query());
    }

    public function create($data): User
    {
        $user = $this->model->create($data);
        if(isset($data['role_id'])){
            $user->roles()->sync($data['role_id']);
        }
        return $user;
    }

    public function detail($id)
    {
        $user = $this->model->findOr($id, fn () => throw new CustomException("User not found"));
        $user->role_id = $user->roles->pluck('id')->toArray();
        return $user;
    }

    public function update($id, $data)
    {
        $user = $this->model->findOr($id, fn () => throw new CustomException("User not found"));
        if (isset($data['password'])) {
            unset($data['password']);
        }
        $user->update($data);
        if(isset($data['role_id'])){
            $user->roles()->sync($data['role_id']);
        }
       
        return $user;
    }

    public function remove($data)
    {
        User::whereIn('id', $data['ids'])->whereNotIn('id', [auth()->id()])->delete();
    }
}
