<?php

namespace App\Services;

use App\Repositories\UserRepository;
use Illuminate\Database\Eloquent\Collection;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Hash; // Penting untuk hashing password
use Illuminate\Validation\ValidationException;

class UserService
{
    protected $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function getAllUsers(): Collection
    {
        return $this->userRepository->getAll();
    }

    public function findById(int $id): ?User
    {
        return $this->userRepository->findById($id);
    }

    public function findByUsername(string $username): ?User
    {
        return $this->userRepository->findByUsername($username);
    }

    public function findByEmail(string $email): ?User
    {
        return $this->userRepository->findByEmail($email);
    }

    public function findByPegawaiId(string $pegawai_id): ?User
    {
        return $this->userRepository->findByPegawaiId($pegawai_id);
    }

    public function createUser(array $data): User
    {
        // Validasi dasar
        if (empty($data['name']) || empty($data['username']) || empty($data['password'])) {
            throw new \Exception("Nama, username, dan password tidak boleh kosong.");
        }

        // Cek apakah email sudah terdaftar
        if ($this->userRepository->findByUsername($data['username'])) {
            throw new \Exception("Username '{$data['username']}' sudah terdaftar.");
        }

        // Hash password sebelum disimpan
        $data['password'] = Hash::make($data['password']);

        return $this->userRepository->create($data);
    }

    public function updateUser(int $id, array $data): ?User
    {
        $user = $this->userRepository->findById($id);

        if (!$user) {
            return null;
        }

        // Jika email diupdate, cek duplikasi (kecuali untuk user itu sendiri)
        if (isset($data['email']) && $data['email'] !== $user->email) {
            if ($this->userRepository->findByEmail($data['email'])) {
                throw new \Exception("Email '{$data['email']}' sudah terdaftar untuk user lain.");
            }
        }

        // Jika password diupdate, hash password baru
        if (isset($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        }

        return $this->userRepository->update($id, $data);
    }

    public function deleteUser(string $username): bool
    {
        $user = $this->userRepository->findByUsername($username);
        if (!$user) {
            throw new Exception('User tidak ditemukan.');
        }

        return $this->userRepository->delete($username);
    }

    public function login(array $credentials): ?User
    {
        $user = $this->userRepository->findByUsername($credentials['username']);

        if (!$user || !Hash::check($credentials['password'], $user->password)) {
            throw new Exception('Username atau password salah.');
        }

        return $user;
    }

    public function logout(): void
    {
        // Logika logout bisa ditambahkan di sini jika diperlukan
        // Misalnya, menghapus token atau sesi pengguna
    }
}
