<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'email'    => 'required|email',
            'password' => 'required|string',
        ]);

        $user = User::where('email', $request->email)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['Email atau password salah.'],
            ]);
        }

        if (!$user->is_aktif) {
            return response()->json([
                'success' => false,
                'message' => 'Akun Anda tidak aktif. Hubungi administrator.',
            ], 403);
        }

        // Load relasi berdasarkan role
        $userData = $user->load($this->getRelationByRole($user->role));

        $token = $user->createToken('auth-token')->plainTextToken;

        return response()->json([
            'success' => true,
            'message' => 'Login berhasil.',
            'data'    => [
                'user'  => $this->formatUser($userData),
                'token' => $token,
            ],
        ]);
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'success' => true,
            'message' => 'Logout berhasil.',
        ]);
    }

    public function profile(Request $request)
    {
        $user = $request->user()->load($this->getRelationByRole($request->user()->role));

        return response()->json([
            'success' => true,
            'data'    => $this->formatUser($user),
        ]);
    }

    public function updateProfile(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'name'         => 'sometimes|string|max:255',
            'password'     => 'sometimes|string|min:6|confirmed',
        ]);

        if ($request->filled('name')) {
            $user->update(['name' => $request->name]);
        }

        if ($request->filled('password')) {
            $user->update(['password' => Hash::make($request->password)]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Profil berhasil diperbarui.',
            'data'    => $this->formatUser($user->fresh()),
        ]);
    }

    private function getRelationByRole(string $role): array
    {
        return match ($role) {
            'guru'  => ['guru'],
            'siswa' => ['siswa.kelas.tingkatSekolah'],
            default => [],
        };
    }

    private function formatUser(User $user): array
    {
        $base = [
            'id'       => $user->id,
            'name'     => $user->name,
            'email'    => $user->email,
            'role'     => $user->role,
            'is_aktif' => $user->is_aktif,
        ];

        if ($user->role === 'guru' && $user->guru) {
            $base['profil'] = $user->guru;
        }

        if ($user->role === 'siswa' && $user->siswa) {
            $base['profil'] = $user->siswa;
        }

        return $base;
    }
}
