<?php

namespace Tests\Feature;

use App\Models\Admin;
use App\Models\Merchant;
use App\Models\Plan;
use App\Models\PlatformOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AdminDashboardPlanOrderShareTop5ShouldLinkToPlatformOrdersListByPlanTest 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_dashboard_plan_order_share_top5_should_link_to_platform_orders_list_by_plan(): void
    {
        $this->loginAsPlatformAdmin();

        $merchant = Merchant::query()->firstOrFail();
        $platformAdminId = (int) Admin::query()->where('email', 'platform.admin@demo.local')->value('id');

        $plan = Plan::query()->create([
            'code' => 'dash_share_top5_link_plan',
            'name' => '仪表盘占比Top5链接测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        // 说明：InitialDemoSeeder 会补齐较多“套餐占比”演示数据；为了确保本用例构造的套餐进入 Top5，
        // 这里需要造足够多的同套餐订单（按“订单数”口径统计）。
        for ($i = 1; $i <= 30; $i++) {
            PlatformOrder::query()->create([
                'merchant_id' => $merchant->id,
                'plan_id' => $plan->id,
                'site_subscription_id' => null,
                'created_by_admin_id' => $platformAdminId ?: null,
                'order_no' => 'PO_DASH_SHARE_LINK_' . str_pad((string) $i, 4, '0', STR_PAD_LEFT),
                'order_type' => 'new_purchase',
                'status' => 'pending',
                'payment_status' => 'paid',
                'payable_amount' => 10,
                'paid_amount' => 10,
                'placed_at' => now(),
                'meta' => [],
            ]);
        }

        $res = $this->get('/admin');
        $res->assertOk();

        // 套餐名应可点击，链接到 platform orders 列表并带 plan_id 与近7天范围
        $res->assertSee($plan->name, false);
        $res->assertSee('/admin/platform-orders?', false);
        $res->assertSee('plan_id=' . (int) $plan->id, false);
        $res->assertSee('created_from=', false);
        $res->assertSee('created_to=', false);
    }
}
