<?php

namespace App\Services;

use App\Models\Incident;
use App\Models\WarRoom;
use App\Models\User;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * War room service: when a critical incident opens, automatically create
 * a Telegram group with the on-call team pre-loaded with incident context.
 * The group archives itself when the incident resolves.
 *
 * Why this matters: critical incidents need fast collaboration. Hunting for
 * the right Slack channel or starting a new chat costs minutes. Auto-spinning
 * a war room means everyone's already there.
 *
 * Telegram groups can't actually be created via Bot API (groups can only be
 * created by users). What we CAN do:
 *
 *   1) Pre-create a pool of generic "war room" groups manually
 *   2) Bot is admin in all of them
 *   3) Service picks an unused one, renames it to incident-specific name
 *   4) Sends incident context + adds anyone marked on-call
 *   5) On resolve, removes everyone and renames back to "Available"
 *
 * For the MVP, we just create a `WarRoom` row pointing to a manual chat link
 * and post the incident summary. The pool-based auto-creation is a future
 * optimization.
 */
class WarRoomService
{
    /**
     * Open a war room for the incident. Returns the WarRoom record.
     */
    public function openForIncident(Incident $incident): ?WarRoom
    {
        if ($incident->severity !== 'critical') {
            return null;
        }

        // Check if one already exists
        $existing = WarRoom::where('incident_id', $incident->id)
            ->whereNull('closed_at')
            ->first();
        if ($existing) return $existing;

        $botToken = config('services.telegram.bot_token');
        $defaultChatId = config('services.telegram.warroom_chat_id');

        if (!$botToken || !$defaultChatId) {
            Log::warning("WarRoom: Telegram not configured");
            return null;
        }

        // Post the incident context to the configured war-room chat
        $message = $this->formatIncidentContext($incident);
        try {
            $resp = Http::timeout(10)->post(
                "https://api.telegram.org/bot{$botToken}/sendMessage",
                [
                    'chat_id' => $defaultChatId,
                    'text' => $message,
                    'parse_mode' => 'Markdown',
                    'disable_web_page_preview' => true,
                ]
            );

            $messageId = $resp->json('result.message_id');

            // We need an opened_by user — when auto-opened (incident open trigger),
            // attribute to the incident's assignee, fallback to first admin.
            $openedBy = $incident->assigned_to
                ?? \App\Models\User::where('role', 'super_admin')->orWhere('role', 'admin')->value('id')
                ?? \App\Models\User::value('id');

            return WarRoom::create([
                'incident_id' => $incident->id,
                'platform' => 'telegram',
                'chat_id' => (string) $defaultChatId,
                'invite_url' => $messageId
                    ? "https://t.me/c/" . ltrim($defaultChatId, '-') . "/{$messageId}"
                    : null,
                'participants' => [
                    'severity' => $incident->severity,
                    'title' => $incident->title,
                    'message_id' => $messageId,
                ],
                'opened_at' => now(),
                'opened_by' => $openedBy,
            ]);
        } catch (\Throwable $e) {
            Log::error("WarRoom create failed: " . $e->getMessage());
            return null;
        }
    }

    /**
     * Closes the war room. Posts a "resolved" summary and marks closed.
     */
    public function closeForIncident(Incident $incident): void
    {
        $room = WarRoom::where('incident_id', $incident->id)
            ->whereNull('closed_at')
            ->first();
        if (!$room) return;

        $botToken = config('services.telegram.bot_token');
        if ($botToken) {
            $duration = $incident->acknowledged_at
                ? $incident->created_at->diffForHumans($incident->updated_at, true)
                : 'unknown';
            $resolvedBy = $incident->resolved_by ? User::find($incident->resolved_by)?->name : 'auto';
            $msg = "✅ *Incident resolved*\n\n" .
                "_{$incident->title}_\n" .
                "Duration: {$duration}\n" .
                "Resolved by: {$resolvedBy}";
            try {
                Http::timeout(5)->post("https://api.telegram.org/bot{$botToken}/sendMessage", [
                    'chat_id' => $room->chat_id,
                    'text' => $msg,
                    'parse_mode' => 'Markdown',
                ]);
            } catch (\Throwable $e) {
                Log::warning("War room close-message failed: " . $e->getMessage());
            }
        }

        $room->update(['closed_at' => now()]);
    }

    /**
     * Markdown-formatted incident context for posting.
     */
    protected function formatIncidentContext(Incident $incident): string
    {
        $hints = '';
        if ($incident->root_cause_hints && is_array($incident->root_cause_hints)) {
            $hints = "\n\n*Root cause hints:*\n";
            foreach (array_slice($incident->root_cause_hints, 0, 5) as $h) {
                $hints .= "• {$h['summary']}\n";
            }
        }

        $url = url('/incidents/' . $incident->id);

        return "🚨 *CRITICAL INCIDENT — WAR ROOM*\n\n" .
            "*{$incident->title}*\n" .
            "Severity: {$incident->severity}\n" .
            "Source: {$incident->source}\n" .
            "Detector: `{$incident->detector_key}`\n" .
            ($incident->description ? "\n{$incident->description}\n" : '') .
            $hints .
            "\n[Open in dashboard]({$url})";
    }
}
