<?php

namespace Tests\Feature;

use App\Models\AppNotification;
use App\Models\Plan;
use App\Models\Subscription;
use App\Models\User;
use App\Services\ApiTokenService;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ReminderDispatchTest extends TestCase
{
    use RefreshDatabase;

    public function test_due_notifications_are_dispatched_and_exposed_via_api(): void
    {
        $plan = Plan::query()->create([
            'name' => 'Pro',
            'slug' => 'pro',
            'price' => 499,
            'billing_cycle' => 'monthly',
            'entry_limit' => 1000,
            'ai_limit' => 100,
            'reminder_limit' => 100,
            'is_active' => true,
            'features' => [
                'manual_entries' => true,
                'ai_input' => true,
                'smart_reminders' => true,
            ],
        ]);

        $user = User::factory()->create([
            'role' => 'customer',
            'status' => 'active',
        ]);

        $subscription = Subscription::query()->create([
            'user_id' => $user->id,
            'plan_id' => $plan->id,
            'status' => 'active',
            'starts_at' => Carbon::now()->subDays(2),
            'ends_at' => Carbon::now()->addMonth(),
        ]);

        $dueNotification = AppNotification::query()->create([
            'user_id' => $user->id,
            'message' => 'Call Mukesh for Rs. 900',
            'type' => 'reminder',
            'status' => 'pending',
            'scheduled_at' => Carbon::now()->subMinutes(5),
        ]);

        AppNotification::query()->create([
            'user_id' => $user->id,
            'message' => 'Tomorrow follow-up',
            'type' => 'reminder',
            'status' => 'pending',
            'scheduled_at' => Carbon::now()->addHour(),
        ]);

        $this->artisan('flowieons:send-reminders')
            ->expectsOutput('Dispatched 1 reminder notification(s).')
            ->assertSuccessful();

        $this->assertDatabaseHas('notifications', [
            'id' => $dueNotification->id,
            'status' => 'sent',
        ]);

        $this->assertDatabaseHas('usage_logs', [
            'user_id' => $user->id,
            'subscription_id' => $subscription->id,
            'feature' => 'reminder',
            'count' => 1,
        ]);

        $token = app(ApiTokenService::class)->issue($user)['plain_text_token'];

        $this->withHeader('Authorization', 'Bearer '.$token)
            ->getJson('/api/v1/notifications/me?status=sent')
            ->assertOk()
            ->assertJsonPath('data.0.id', $dueNotification->id)
            ->assertJsonPath('data.0.status', 'sent');
    }
}
