<?php

namespace App\Http\Controllers\Admin\Settings;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Settings\ProfileDeleteRequest;
use App\Http\Requests\Admin\Settings\ProfileUpdateRequest;
use App\Models\User;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Inertia\Response;

class ProfileController extends Controller
{
    public function edit(Request $request): Response
    {
        $user = $request->user();

        [$role, $roleData] = match (true) {
            $user->hasRole('mahasiswa') => $this->studentRoleData($user),
            $user->hasRole('dosen') => $this->lecturerRoleData($user),
            default => $this->administratorRoleData($user),
        };

        return Inertia::render('admin/settings/profile', [
            'mustVerifyEmail' => $user instanceof MustVerifyEmail,
            'status' => $request->session()->get('status'),
            'profile' => $user->profile,
            'role' => $role,
            'roleData' => $roleData,
        ]);
    }

    public function update(ProfileUpdateRequest $request): RedirectResponse
    {
        $user = $request->user();

        $user->fill($request->safe()->only(['username', 'email']));

        if ($user->isDirty('email')) {
            $user->email_verified_at = null;
        }

        $user->save();

        $user->profile()->updateOrCreate([], $request->safe()->only([
            'full_name', 'phone_number', 'address', 'gender', 'birth_date', 'birth_place',
        ]));

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Profil berhasil diperbarui.']);

        return to_route('admin.settings.profile.edit');
    }

    public function destroy(ProfileDeleteRequest $request): RedirectResponse
    {
        $user = $request->user();

        Auth::logout();

        $user->delete();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/');
    }

    private function studentRoleData(User $user): array
    {
        $user->load(['profile', 'student.department', 'student.academicAdvisor.user.profile']);

        return ['mahasiswa', $user->student ? [
            'student_number' => $user->student->student_number,
            'department' => $user->student->department?->name,
            'enrollment_year' => $user->student->enrollment_year,
            'academic_advisor' => $user->student->academicAdvisor?->user?->profile?->full_name,
        ] : null];
    }

    private function lecturerRoleData(User $user): array
    {
        $user->load(['profile', 'lecturer.departments']);

        return ['dosen', $user->lecturer ? [
            'lecturer_number' => $user->lecturer->lecturer_number,
            'department' => $user->lecturer->departments->pluck('name')->join(', ') ?: null,
        ] : null];
    }

    private function administratorRoleData(User $user): array
    {
        $user->load(['profile', 'roles']);

        return ['admin', [
            'roles' => $user->roles->pluck('name')->all(),
        ]];
    }
}
