<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\Notification\Models\PushAnalytic;
use App\Domain\Shared\Models\DeviceToken;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PushAnalyticsController extends Controller
{
    public function track(Request $request): JsonResponse
    {
        $request->validate([
            'events' => 'required|array|min:1|max:50',
            'events.*.notification_id' => 'nullable|string|max:100',
            'events.*.event_type' => 'required|string|max:50',
            'events.*.action' => 'required|in:delivered,opened,dismissed,action_clicked',
            'events.*.metadata' => 'nullable|array',
        ]);

        $user = $request->user();
        $now = now();

        $records = array_map(fn ($event) => [
            'academy_id' => $user->academy_id,
            'user_id' => $user->id,
            'notification_id' => $event['notification_id'] ?? null,
            'event_type' => $event['event_type'],
            'action' => $event['action'],
            'metadata' => json_encode($event['metadata'] ?? []),
            'created_at' => $now,
        ], $request->events);

        PushAnalytic::insert($records);

        return response()->json(['tracked' => count($records)]);
    }

    public function badge(Request $request): JsonResponse
    {
        $user = $request->user();

        $unread = \App\Domain\Notification\Models\NotificationLog::where('recipient_type', 'user')
            ->where('recipient_id', $user->id)
            ->whereIn('channel', ['in_app', 'push'])
            ->whereNull('read_at')
            ->where('status', 'sent')
            ->count();

        return response()->json([
            'badge_count' => $unread,
        ]);
    }

    public function heartbeat(Request $request): JsonResponse
    {
        $request->validate([
            'token' => 'required|string|max:255',
        ]);

        DeviceToken::withoutGlobalScope('academy')
            ->where('device_token', $request->token)
            ->where('user_id', $request->user()->id)
            ->update(['last_used_at' => now()]);

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