<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function register(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:8',
            'role' => 'nullable|string',
        ]);
        $data['password'] = Hash::make($data['password']);
        $user = User::create($data);
        return response()->json(['code' => 201, 'user' => $user], 201);
    }

    public function login(Request $request): JsonResponse
    {
        $data = $request->validate([
            'email' => 'required|email',
            'password' => 'required|string',
        ]);
        $user = User::where('email', $data['email'])->first();
        if (!$user || !Hash::check($data['password'], $user->password)) {
            return response()->json(['code' => 401, 'message' => 'Invalid credentials'], 401);
        }
        $access = $user->createToken('access', ['*'], Carbon::now()->addHours(24));
        $refresh = $user->createToken('refresh', ['refresh'], Carbon::now()->addDays(30));
        return response()->json([
            'code' => 200,
            'user' => $user,
            'tokens' => [
                'access' => [
                    'token' => $access->plainTextToken,
                    'expires' => $access->accessToken->expires_at,
                ],
                'refresh' => [
                    'token' => $refresh->plainTextToken,
                    'expires' => $refresh->accessToken->expires_at,
                ],
            ],
        ]);
    }

    public function logout(Request $request): JsonResponse
    {
        if ($request->user()) {
            $request->user()->tokens()->delete();
        }
        return response()->json(['code' => 200, 'message' => 'Logged out']);
    }

    public function changePassword(Request $request): JsonResponse
    {
        $data = $request->validate([
            'email' => 'nullable|email',
            'oldPassword' => 'required|string',
            'newPassword' => 'required|string|min:8',
        ]);
        $user = $request->user();
        if (!$user && !empty($data['email'])) {
            $user = User::where('email', $data['email'])->first();
        }
        if (!$user || !Hash::check($data['oldPassword'], $user->password)) {
            return response()->json(['code' => 400, 'message' => 'Old password incorrect'], 400);
        }
        $user->password = Hash::make($data['newPassword']);
        $user->save();
        return response()->json(['code' => 200, 'message' => 'Password updated']);
    }
}
