<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Auth\LoginRequest;
use App\Http\Requests\Auth\PinLoginRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends ApiController
{
    public function login(LoginRequest $request): JsonResponse
    {
        $user = User::query()
            ->with(['company', 'branch', 'role.permissions'])
            ->where('email', $request->string('email'))
            ->where('is_active', true)
            ->first();

        $passwordCorrect = $user->password && Hash::check($request->string('password'), $user->password);
        $pinCorrect = !$user->password && $user->pin && Hash::check($request->string('password'), $user->pin);

        if ($user === null || (!$passwordCorrect && !$pinCorrect)) {
            throw ValidationException::withMessages([
                'email' => ['Invalid credentials.'],
            ]);
        }

        return $this->issueTokenResponse($user, $request->string('device_name')->toString() ?: 'flutter-pos');
    }

    public function pinLogin(PinLoginRequest $request): JsonResponse
    {
        $user = User::query()
            ->with(['company', 'branch', 'role.permissions'])
            ->where('email', $request->string('email'))
            ->where('is_active', true)
            ->first();

        if ($user === null || empty($user->pin) || ! Hash::check($request->string('pin'), $user->pin)) {
            throw ValidationException::withMessages([
                'pin' => ['Invalid PIN credentials.'],
            ]);
        }

        return $this->issueTokenResponse($user, $request->string('device_name')->toString() ?: 'pos-pin-login');
    }

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

        return response()->json(['message' => 'Logged out successfully.']);
    }

    public function me(Request $request): UserResource
    {
        return new UserResource(
            $request->user()->loadMissing(['company', 'branch', 'role.permissions'])
        );
    }

    private function issueTokenResponse(User $user, string $deviceName): JsonResponse
    {
        $user->forceFill([
            'last_login_at' => now(),
            'last_login_ip' => request()->ip(),
        ])->save();

        $token = $user->createToken($deviceName)->plainTextToken;

        return response()->json([
            'token' => $token,
            'token_type' => 'Bearer',
            'user' => new UserResource($user),
        ]);
    }
}
