<?php

namespace App\Http\Controllers;

use App\Campaigns\PerformanceBoard;
use App\Campaigns\PerformanceVerdict;
use App\Campaigns\PerformanceWindows;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Laravel\Ai\Models\Conversation;

class CampaignPerformanceController extends Controller
{
    public function index(Request $request, PerformanceBoard $board): View
    {
        $data = $board->forUser($request->user(), [
            'q' => (string) $request->query('q', ''),
            'platform' => (string) $request->query('platform', ''),
            'status' => (string) $request->query('status', ''),
            'per_page' => (int) $request->query('per_page', 10),
        ]);

        return view('campaigns.performance', [
            'rows' => $data['rows'],
            'stats' => $data['stats'],
            'totals' => $data['totals'],
            'verdicts' => PerformanceVerdict::cases(),
            'conversations' => $this->conversations($request),
        ]);
    }

    public function show(Request $request, PerformanceBoard $board, string $platform, string $campaign): View
    {
        $detail = $board->detailFor($request->user(), $platform, $campaign, [
            'per_page' => (int) $request->query('per_page', 10),
            'log_run_type' => (string) $request->query('log_run_type', ''),
            'log_verdict' => (string) $request->query('log_verdict', ''),
            'log_days' => (int) $request->query('log_days', 0),
            'log_per_page' => (int) $request->query('log_per_page', 10),
        ]);

        abort_if($detail === null, 404);

        return view('campaigns.performance-show', [
            ...$detail,
            'verdicts' => PerformanceVerdict::cases(),
            'window_keys' => PerformanceWindows::orderedWindowKeys(),
            'conversations' => $this->conversations($request),
        ]);
    }

    /**
     * @return Collection<int, Conversation>
     */
    /**
     * The sidebar list, scoped to whoever is asking.
     *
     * This was an unscoped Conversation::query(), so the sidebar and the search
     * modal on this page rendered other people's chat titles and linked to
     * their conversation ids. The scoping in ChatController exists precisely to
     * stop that, and the sidebar composer only fills the list when the page has
     * not supplied one - so supplying an unscoped list here actively defeated
     * it. ChatListIsScopedTest covers /chats, the dashboard and the chat page,
     * and did not cover this route.
     *
     * Participant-less rows are included for the same reason ChatController
     * includes them: they predate ownership being tracked and mayOpen() still
     * opens them, so hiding them here while the URL works is a different drift.
     *
     * @return Collection<int, Conversation>
     */
    private function conversations(Request $request): Collection
    {
        $user = $request->user();

        if ($user === null) {
            return collect();
        }

        return Conversation::query()
            ->where(fn ($scope) => $scope
                ->whereNull('participant_id')
                ->orWhere(fn ($mine) => $mine
                    ->where('participant_type', $user->getMorphClass())
                    ->where('participant_id', $user->getAuthIdentifier())))
            ->latest('updated_at')
            ->limit(30)
            ->get();
    }
}
