<?php

namespace App\Http\Controllers\Telegram;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\TelegramService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class WebhookController extends Controller
{
    public function __invoke(Request $request, TelegramService $telegram)
    {
        $secret = config('services.telegram.webhook_secret') ?: env('TELEGRAM_WEBHOOK_SECRET');
        if ($secret) {
            $header = (string) $request->header('X-Telegram-Bot-Api-Secret-Token', '');
            if (!hash_equals($secret, $header)) {
                return response()->json(['ok' => false], 401);
            }
        }

        $update = $request->all();

        $message = $update['message'] ?? null;
        if (!$message) {
            return response()->json(['ok' => true]);
        }

        $text = trim((string) ($message['text'] ?? ''));
        if ($text === '' || !Str::startsWith($text, '/start')) {
            return response()->json(['ok' => true]);
        }

        // Telegram sends "/start <payload>"
        $parts = preg_split('/\s+/', $text);
        $token = $parts[1] ?? null;

        $chatId = $message['chat']['id'] ?? null;
        if (!$chatId) {
            return response()->json(['ok' => true]);
        }

        if (!$token) {
            $telegram->sendMessage(
                $chatId,
                "Tu chat_id es: {$chatId}\n\n" .
                "Si eres repartidor, abre el enlace de conexión desde tu perfil para vincular la cuenta.\n" .
                "Si eres admin, coloca este chat_id en TELEGRAM_ADMIN_CHAT_ID."
            );
            return response()->json(['ok' => true]);
        }

        $user = User::query()
            ->where('telegram_connect_token', $token)
            ->first();

        if (!$user) {
            $telegram->sendMessage($chatId, "No pude vincular tu cuenta. Pide al administrador un nuevo enlace de conexion.");
            return response()->json(['ok' => true]);
        }

        $user->forceFill([
            'telegram_chat_id' => (int) $chatId,
            'telegram_connected_at' => now(),
            // Rotate the token after successful linking.
            'telegram_connect_token' => Str::random(64),
        ])->save();

        $telegram->sendMessage($chatId, "Listo. Tu cuenta fue vinculada a TAKS Delivery. Recibiras alertas cuando te asignen pedidos.");

        return response()->json(['ok' => true]);
    }
}
