<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Jobs\SendNotification;
use App\Models\ActivityLog;
use App\Models\NotificationDelivery;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

/**
 * Read-only delivery log + manual retry. Useful for "why didn't I get the
 * alert?" debugging — every send attempt is here with status, attempts,
 * last error, and the rendered body.
 */
class NotificationDeliveryController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = NotificationDelivery::query()
            ->with('recipient:id,name,avatar')
            ->latest();

        if ($f = $request->string('channel')->toString()) $query->where('channel_key', $f);
        if ($s = $request->string('status')->toString()) $query->where('status', $s);
        if ($q = $request->string('q')->toString()) {
            $query->where(function ($w) use ($q) {
                $w->where('recipient_address', 'like', "%{$q}%")
                  ->orWhere('error_message', 'like', "%{$q}%");
            });
        }

        $perPage = min(100, max(10, (int) $request->integer('per_page', 50)));
        $rows = $query->paginate($perPage);

        return response()->json([
            'data' => $rows->items(),
            'meta' => [
                'current_page' => $rows->currentPage(),
                'last_page' => $rows->lastPage(),
                'total' => $rows->total(),
            ],
            'summary' => [
                'sent_24h' => NotificationDelivery::where('status', 'sent')->where('sent_at', '>=', now()->subDay())->count(),
                'failed_24h' => NotificationDelivery::where('status', 'failed')->where('updated_at', '>=', now()->subDay())->count(),
                'queued' => NotificationDelivery::where('status', 'queued')->count(),
                'retrying' => NotificationDelivery::where('status', 'retrying')->count(),
            ],
        ]);
    }

    public function show(NotificationDelivery $delivery): JsonResponse
    {
        $delivery->load('recipient:id,name,email,avatar', 'rule:id,name');
        return response()->json(['data' => $delivery]);
    }

    /**
     * Force-retry a failed/retrying delivery. Bypasses the next_retry_at gate.
     */
    public function retry(Request $request, NotificationDelivery $delivery): JsonResponse
    {
        abort_unless($request->user()->canModifySettings(), 403);

        if ($delivery->status === NotificationDelivery::STATUS_SENT) {
            return response()->json(['ok' => false, 'error' => 'Already sent']);
        }

        $delivery->update(['next_retry_at' => null, 'status' => NotificationDelivery::STATUS_QUEUED]);
        SendNotification::dispatch($delivery->id)->onQueue('notifications');

        ActivityLog::log([
            'action' => 'manually retried delivery',
            'target' => "#{$delivery->id} ({$delivery->channel_key})",
            'category' => 'notifications',
            'severity' => 'low',
        ]);

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