<?php

namespace Tests\Feature;

use App\Models\Merchant;
use App\Models\Plan;
use App\Models\SiteSubscription;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AdminSiteSubscriptionExpiryFilterShouldWorkTest extends TestCase
{
    use RefreshDatabase;

    protected function loginAsPlatformAdmin(): void
    {
        $this->seed();

        $this->post('/admin/login', [
            'email' => 'platform.admin@demo.local',
            'password' => 'Platform@123456',
        ])->assertRedirect('/admin');
    }

    public function test_expiry_filters_should_work(): void
    {
        Carbon::setTestNow(Carbon::parse('2026-03-15 10:00:00'));

        $this->loginAsPlatformAdmin();

        $merchantId = (int) Merchant::query()->value('id');
        $planId = (int) Plan::query()->value('id');

        SiteSubscription::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => $planId,
            'status' => 'activated',
            'source' => 'manual',
            'subscription_no' => 'SUB-EXPIRED-1',
            'plan_name' => '测试套餐',
            'billing_cycle' => 'monthly',
            'period_months' => 1,
            'amount' => 99,
            'starts_at' => now()->subDays(30),
            'ends_at' => now()->subDay(),
            'activated_at' => now()->subDays(30),
        ]);

        SiteSubscription::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => $planId,
            'status' => 'activated',
            'source' => 'manual',
            'subscription_no' => 'SUB-EXPIRING-1',
            'plan_name' => '测试套餐',
            'billing_cycle' => 'monthly',
            'period_months' => 1,
            'amount' => 99,
            'starts_at' => now()->subDays(30),
            'ends_at' => now()->addDays(6),
            'activated_at' => now()->subDays(30),
        ]);

        SiteSubscription::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => $planId,
            'status' => 'activated',
            'source' => 'manual',
            'subscription_no' => 'SUB-LATER-1',
            'plan_name' => '测试套餐',
            'billing_cycle' => 'monthly',
            'period_months' => 1,
            'amount' => 99,
            'starts_at' => now()->subDays(30),
            'ends_at' => now()->addDays(20),
            'activated_at' => now()->subDays(30),
        ]);

        $res = $this->get('/admin/site-subscriptions?expiry=expired');
        $res->assertOk();
        $res->assertSee('SUB-EXPIRED-1');
        $res->assertDontSee('SUB-EXPIRING-1');
        $res->assertDontSee('SUB-LATER-1');

        $res = $this->get('/admin/site-subscriptions?expiry=expiring_7d');
        $res->assertOk();
        $res->assertSee('SUB-EXPIRING-1');
        $res->assertDontSee('SUB-EXPIRED-1');
        $res->assertDontSee('SUB-LATER-1');
    }
}
