<?php

namespace App\Services\Admin\Users;

use App\Models\Lecturer;
use App\Models\User;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class LecturerService
{
    public function getAllForSelect(): Collection
    {
        return Lecturer::select(['id', 'user_id', 'lecturer_number'])
            ->with([
                'user:id,username',
                'user.profile:id,user_id,full_name',
                'departments:id,name',
            ])
            ->get();
    }

    public function paginated(int $perPage = 25, string $search = '', ?string $gender = null, ?int $departmentId = null): LengthAwarePaginator
    {
        return $this->filteredQuery($search, $gender, $departmentId)
            ->latest()
            ->paginate($perPage);
    }

    public function forExport(string $search = '', ?string $gender = null, ?int $departmentId = null): Collection
    {
        return $this->filteredQuery($search, $gender, $departmentId)
            ->orderBy('created_at', 'desc')
            ->get();
    }

    private function filteredQuery(string $search, ?string $gender, ?int $departmentId): Builder
    {
        return User::select(['id', 'username', 'email', 'is_active'])
            ->with([
                'profile:id,user_id,full_name,phone_number,gender,birth_place,birth_date,address',
                'lecturer:id,user_id,lecturer_number',
                'lecturer.departments:id,name',
            ])
            ->whereHas('roles', fn ($q) => $q->where('name', 'dosen'))
            ->when($search, fn ($q) => $q->where(function ($query) use ($search) {
                $query->where('username', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhereHas('profile', fn ($q) => $q->where('full_name', 'like', "%{$search}%"))
                    ->orWhereHas('lecturer', fn ($q) => $q->where('lecturer_number', 'like', "%{$search}%"));
            }))
            ->when($gender, fn ($q) => $q->whereHas('profile', fn ($q) => $q->where('gender', $gender)))
            ->when($departmentId, fn ($q) => $q->whereHas('lecturer.departments', fn ($q) => $q->where('departments.id', $departmentId)));
    }

    public function create(array $data): User
    {
        return DB::transaction(function () use ($data) {
            $user = User::create([
                'username' => $data['username'],
                'email' => $data['email'],
                'password' => Hash::make(config('app.default_password')),
            ]);

            $user->assignRole('dosen');

            $user->profile()->create([
                'full_name' => $data['full_name'],
                'phone_number' => $data['phone_number'],
                'address' => $data['address'],
                'gender' => $data['gender'],
                'birth_date' => $data['birth_date'],
                'birth_place' => $data['birth_place'],
            ]);

            $lecturer = $user->lecturer()->create([
                'lecturer_number' => $data['lecturer_number'],
            ]);

            $lecturer->departments()->sync($data['department_ids']);

            return $user;
        });
    }

    public function update(User $user, array $data): User
    {
        DB::transaction(function () use ($user, $data) {
            $user->update([
                'username' => $data['username'],
                'email' => $data['email'],
            ]);

            $user->profile()->updateOrCreate([], [
                'full_name' => $data['full_name'],
                'phone_number' => $data['phone_number'],
                'address' => $data['address'],
                'gender' => $data['gender'],
                'birth_date' => $data['birth_date'],
                'birth_place' => $data['birth_place'],
            ]);

            $lecturer = $user->lecturer()->updateOrCreate([], [
                'lecturer_number' => $data['lecturer_number'],
            ]);

            $lecturer->departments()->sync($data['department_ids']);
        });

        return $user->fresh(['profile', 'lecturer.departments', 'roles']);
    }

    public function delete(User $user): void
    {
        DB::transaction(function () use ($user) {
            $user->lecturer()->delete();
            $user->profile()->delete();
            $user->delete();
        });
    }

    public function resetPassword(User $user): void
    {
        $user->update([
            'password' => Hash::make(config('app.default_password')),
        ]);
    }

    public function updateUserStatus(User $user, bool $isActive): void
    {
        $user->update(['is_active' => $isActive]);
    }
}
