<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Services\NotificationService;
use App\Services\TelegramLinkService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * Endpoints used by the admin profile page to:
 *   - generate Telegram deep-link tokens
 *   - test each notification channel with a sample message
 *   - check current connection status
 */
class AdminChannelTestController extends Controller
{
    public function __construct(
        private readonly NotificationService $notificationService,
        private readonly TelegramLinkService $telegramLinkService,
    ) {}

    /**
     * GET /api/v1/admin/profile/channels/status
     * Returns which channels are configured at the admin + system level.
     */
    public function status(Request $request): JsonResponse
    {
        $admin = $request->user();

        return response()->json([
            'admin' => [
                'slack' => !empty($admin->slack_user_id),
                'telegram' => !empty($admin->telegram_user_id),
                'discord' => !empty($admin->discord_webhook),
                'teams' => !empty($admin->teams_webhook),
                'pushover' => !empty($admin->pushover_user_key),
                'whatsapp' => !empty($admin->phone),
                'sms' => !empty($admin->phone),
                'email' => !empty($admin->email),
            ],
            'system' => [
                'slack' => !empty(Setting::get('slack_bot_token')),
                'telegram' => !empty(Setting::get('telegram_bot_token')),
                'discord' => true, // webhook-based, no system dep
                'teams' => true, // webhook-based, no system dep
                'pushover' => !empty(Setting::get('pushover_app_token')),
                'whatsapp' => !empty(Setting::get('whatsapp_api_token')) && !empty(Setting::get('whatsapp_phone_number_id')),
                'sms' => true, // SMS has its own settings tab
                'email' => true,
            ],
            'telegram_bot_username' => $this->telegramLinkService->getBotUsername(),
        ]);
    }

    /**
     * POST /api/v1/admin/profile/channels/telegram/link
     * Generates a single-use Telegram deep-link URL for this admin.
     */
    public function telegramLink(Request $request): JsonResponse
    {
        $admin = $request->user();

        $url = $this->telegramLinkService->generateDeepLink($admin->id);

        if (!$url) {
            return response()->json([
                'ok' => false,
                'error' => 'telegram_not_configured',
                'message' => __('profile.bot_not_configured_telegram'),
            ], 422);
        }

        return response()->json([
            'ok' => true,
            'url' => $url,
            'expires_in_seconds' => 600,
        ]);
    }

    /**
     * POST /api/v1/admin/profile/channels/telegram/unlink
     * Clears the admin's telegram_user_id.
     */
    public function telegramUnlink(Request $request): JsonResponse
    {
        $admin = $request->user();
        $admin->update(['telegram_user_id' => null]);

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

    /**
     * POST /api/v1/admin/profile/channels/{channel}/test
     * Sends a test notification to the requested channel using live credentials.
     * Returns {ok: true} on success or a clear error message.
     */
    public function test(Request $request, string $channel): JsonResponse
    {
        $admin = $request->user();

        $allowed = ['slack', 'telegram', 'discord', 'teams', 'pushover', 'whatsapp', 'sms', 'email'];
        if (!in_array($channel, $allowed, true)) {
            return response()->json(['ok' => false, 'error' => 'invalid_channel'], 422);
        }

        // Validate admin has the target address configured
        $missing = match ($channel) {
            'slack' => empty($admin->slack_user_id),
            'telegram' => empty($admin->telegram_user_id),
            'discord' => empty($admin->discord_webhook),
            'teams' => empty($admin->teams_webhook),
            'pushover' => empty($admin->pushover_user_key),
            'whatsapp', 'sms' => empty($admin->phone),
            'email' => empty($admin->email),
            default => true,
        };

        if ($missing) {
            return response()->json([
                'ok' => false,
                'error' => 'channel_not_configured',
                'message' => __('profile.test_error_not_configured'),
            ], 422);
        }

        // Validate system-level prerequisites
        $systemMissing = match ($channel) {
            'slack' => empty(Setting::get('slack_bot_token')),
            'telegram' => empty(Setting::get('telegram_bot_token')),
            'pushover' => empty(Setting::get('pushover_app_token')),
            'whatsapp' => empty(Setting::get('whatsapp_api_token')) || empty(Setting::get('whatsapp_phone_number_id')),
            default => false,
        };

        if ($systemMissing) {
            return response()->json([
                'ok' => false,
                'error' => 'system_not_configured',
                'message' => __('profile.test_error_system_not_configured'),
            ], 422);
        }

        $subject = __('profile.test_subject');
        $message = __('profile.test_message', ['name' => $admin->name]);

        try {
            $this->sendTestMessage($admin, $channel, $subject, $message);
        } catch (\Exception $e) {
            Log::error('Channel test failed', [
                'channel' => $channel,
                'admin_id' => $admin->id,
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'ok' => false,
                'error' => 'send_failed',
                'message' => $e->getMessage(),
            ], 500);
        }

        return response()->json([
            'ok' => true,
            'message' => __('profile.test_sent_success'),
        ]);
    }

    /**
     * Dispatch a simple test message synchronously so the caller gets real
     * success/failure feedback instead of a queue ack.
     */
    private function sendTestMessage($admin, string $channel, string $subject, string $message): void
    {
        switch ($channel) {
            case 'slack':
                $botToken = Setting::get('slack_bot_token');
                $response = Http::withToken($botToken)
                    ->post('https://slack.com/api/chat.postMessage', [
                        'channel' => $admin->slack_user_id,
                        'text' => "*{$subject}*\n{$message}",
                    ]);
                $data = $response->json();
                if (!($data['ok'] ?? false)) {
                    throw new \RuntimeException('Slack: ' . ($data['error'] ?? 'unknown_error'));
                }
                break;

            case 'telegram':
                // PRC-175: Markdown parse_mode kaldırıldı — $message içinde
                // `__('profile.test_message', ['name' => $admin->name])`
                // ile admin'in kendi adı interpolate ediliyor; admin
                // name'inde `[link](url)` veya `_italic_` kullanırsa
                // bot'un paylaşıldığı kanalda yanıltıcı render olur.
                // Plain text default Telegram parse mode'u (HTML/Markdown
                // yok); admin name'i ham gösterilir.
                $botToken = Setting::get('telegram_bot_token');
                $response = Http::post("https://api.telegram.org/bot{$botToken}/sendMessage", [
                    'chat_id' => $admin->telegram_user_id,
                    'text' => "{$subject}\n{$message}",
                ]);
                $data = $response->json();
                if (!($data['ok'] ?? false)) {
                    throw new \RuntimeException('Telegram: ' . ($data['description'] ?? 'unknown_error'));
                }
                break;

            case 'discord':
                $response = Http::post($admin->discord_webhook, [
                    'content' => "**{$subject}**\n{$message}",
                ]);
                if ($response->failed()) {
                    throw new \RuntimeException('Discord: HTTP ' . $response->status());
                }
                break;

            case 'teams':
                // PRC-782 — Teams Workflows webhook basit {"text": "..."} kabul eder (Markdown)
                $response = Http::post($admin->teams_webhook, [
                    'text' => "**{$subject}**\n\n{$message}",
                ]);
                if ($response->failed()) {
                    throw new \RuntimeException('Teams: HTTP ' . $response->status());
                }
                break;

            case 'pushover':
                $appToken = Setting::get('pushover_app_token');
                $response = Http::asForm()->post('https://api.pushover.net/1/messages.json', [
                    'token' => $appToken,
                    'user' => $admin->pushover_user_key,
                    'title' => $subject,
                    'message' => $message,
                ]);
                $data = $response->json();
                if (($data['status'] ?? 0) !== 1) {
                    $errors = $data['errors'] ?? ['unknown_error'];
                    throw new \RuntimeException('Pushover: ' . implode(', ', $errors));
                }
                break;

            case 'whatsapp':
                $token = Setting::get('whatsapp_api_token');
                $phoneNumberId = Setting::get('whatsapp_phone_number_id');
                $response = Http::withToken($token)
                    ->post("https://graph.facebook.com/v18.0/{$phoneNumberId}/messages", [
                        'messaging_product' => 'whatsapp',
                        'to' => $admin->phone,
                        'type' => 'text',
                        'text' => ['body' => "{$subject}\n{$message}"],
                    ]);
                if ($response->failed()) {
                    $err = $response->json('error.message', 'unknown_error');
                    throw new \RuntimeException('WhatsApp: ' . $err);
                }
                break;

            case 'sms':
                app(\App\Services\SmsService::class)->send($admin->phone, "{$subject}\n{$message}");
                break;

            case 'email':
                \App\Jobs\SendEmailJob::dispatch(
                    'Admin Notification',
                    'system',
                    0,
                    [
                        'SUBJECT' => $subject,
                        'NOTIFICATION_MESSAGE' => $message,
                        'ADMIN_NAME' => $admin->name,
                    ],
                    null,
                    $admin->email
                );
                break;
        }
    }
}
