<?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 Illuminate\Support\Facades\Cache;
use Tests\TestCase;

class AdminDashboardPlanOrderShareMiniChartShouldHaveLinkSourceInTableTest 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_plan_order_share_mini_chart_should_have_link_source_in_table(): void
    {
        Cache::flush();

        $this->loginAsPlatformAdmin();

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

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

        // 构造足够多订单，确保该套餐进入 Top5（避免 seed 数据干扰 Top5 排序）
        $ids = [];
        for ($i = 1; $i <= 10; $i++) {
            $po = 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_PLAN_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' => [],
            ]);
            $ids[] = (int) $po->id;
        }

        // 确保命中近7天 created_at 口径
        PlatformOrder::query()->whereIn('id', $ids)->update([
            'created_at' => now()->startOfDay(),
            'updated_at' => now()->startOfDay(),
        ]);

        Cache::flush();

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

        // 套餐占比迷你图（JS 渐进增强）复用表格中套餐链接口径，因此这里做“表格链接存在”护栏。
        $res->assertSee('data-role="plan-order-share-top5"', false);
        $res->assertSee('data-role="plan-order-share-top5-chart"', false);

        // 表格中套餐名称应为可点击链接，且带 plan_id 与近7天范围。
        $res->assertSee($plan->name, false);
        $res->assertSee('plan_id=' . (int) $plan->id, false);
        $res->assertSee('created_from=', false);
        $res->assertSee('created_to=', false);
    }
}
