<?php

namespace Tests\Feature;

use App\Models\Admin;
use App\Models\Merchant;
use App\Models\PlatformOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;

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

        $this->loginAsPlatformAdmin();

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

        $d3 = now()->subDays(3)->format('Y-m-d');

        $po = PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => null,
            'site_subscription_id' => null,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_TREND_CHART_LINK_D3',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'paid',
            'payable_amount' => 10,
            'paid_amount' => 10,
        ]);

        PlatformOrder::query()->where('id', $po->id)->update([
            'created_at' => now()->subDays(3)->startOfDay(),
            'updated_at' => now()->subDays(3)->startOfDay(),
        ]);

        Cache::flush();

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

        // 迷你图表的链接不是 SSR 输出（由 JS 渐进增强渲染），
        // 但它依赖下方表格中的日期链接口径，因此这里至少做“表格日期链接存在”护栏。
        // 若未来有人把表格链接删掉/改成非 <a>，迷你图表将失去跳转能力。
        $res->assertSee('data-role="platform-order-trend-7d"', false);
        $res->assertSee('data-role="platform-order-trend-7d-chart"', false);

        // 日期列应为可点击链接
        $res->assertSee('>' . $d3 . '</a>', false);
        $res->assertSee('created_from=' . $d3, false);
        $res->assertSee('created_to=' . $d3, false);
    }
}
