<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\AuthTelegramLink;
use App\Models\User;
use App\Support\Security\TelegramVerifier;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TelegramLoginController extends Controller
{
    public function __construct(private readonly TelegramVerifier $verifier)
    {
    }

    public function callback(Request $request): RedirectResponse
    {
        $botToken = (string) config('services.telegram.bot_token');
        $payload = $request->only(['id', 'first_name', 'username', 'photo_url', 'auth_date', 'hash']);

        if ($botToken === '' || ! $this->verifier->verify($payload, $botToken)) {
            return redirect()->route('login')->withErrors(['telegram' => 'Telegram login verification failed.']);
        }

        $telegramId = (string) $payload['id'];
        $link = AuthTelegramLink::query()->where('telegram_id', $telegramId)->first();

        if ($link) {
            $user = User::query()->findOrFail($link->user_id);
        } else {
            $baseUsername = 'tg_'.$telegramId;
            $username = User::query()->where('username', $baseUsername)->exists()
                ? $baseUsername.'_'.substr($telegramId, -4)
                : $baseUsername;

            $user = User::query()->create([
                'username' => $username,
                'email' => $username.'@telegram.local',
                'password' => null,
                'status' => 'active',
            ]);

            AuthTelegramLink::query()->create([
                'user_id' => $user->id,
                'telegram_id' => $telegramId,
                'telegram_username' => $payload['username'] ?? null,
                'first_name' => $payload['first_name'] ?? null,
                'photo_url' => $payload['photo_url'] ?? null,
                'linked_at' => now(),
            ]);
        }

        Auth::login($user);
        $request->session()->regenerate();

        return redirect()->route('wallet.dashboard');
    }
}
