<?php

namespace App\Http\Controllers\Api;

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

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

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

        if (! $user || ! Hash::check($request->password, $user->password)) {
            return response()->json([
                'success' => false,
                'message' => 'Die Anmeldedaten sind ungültig.',
                'errors' => [],
            ], 401);
        }

        $token = Str::random(64);
        $user->tokens()->create([
            'token' => hash('sha256', $token),
            'name' => $request->header('User-Agent', 'API'),
        ]);

        return response()->json([
            'success' => true,
            'data' => [
                'token' => $token,
                'user' => $user->only(['id', 'name', 'email', 'locale', 'timezone']),
            ],
            'message' => 'Erfolgreich angemeldet.',
        ]);
    }

    public function logout(Request $request): JsonResponse
    {
        $bearer = $request->bearerToken();

        if ($bearer) {
            $request->user()->tokens()
                ->where('token', hash('sha256', $bearer))
                ->delete();
        }

        return response()->json([
            'success' => true,
            'data' => null,
            'message' => 'Erfolgreich abgemeldet.',
        ]);
    }

    public function me(Request $request): JsonResponse
    {
        $user = $request->user();
        $user->load('subscription.plan');

        return response()->json([
            'success' => true,
            'data' => [
                'id'       => $user->id,
                'locale'   => $user->locale ?? 'de',
                'timezone' => $user->timezone ?? 'Europe/Vienna',
                'user' => $user->only(['id', 'name', 'email', 'locale', 'timezone', 'settings', 'role']),
                'plan' => $user->subscription?->plan?->only(['id', 'name', 'plan_key', 'credit_limit']),
                'usage' => [
                    'credits_used' => $user->monthly_usage,
                    'credits_limit' => $user->effective_limit,
                    'usage_percent' => $user->usage_percent,
                    'bonus_credits' => $user->bonus_credits,
                ],
            ],
        ]);
    }
}
