<?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 AdminDashboardPlatformOrderTrend7dShouldRenderTest 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_platform_order_trend_7d_should_render(): 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');
        $d0 = now()->format('Y-m-d');

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

        $po2 = PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => null,
            'site_subscription_id' => null,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_TREND_D0',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'payable_amount' => 20,
            'paid_amount' => 0,
        ]);

        // 强制把 created_at 调整到目标日期（避免依赖 create() 的当前时间）
        PlatformOrder::query()->where('id', $po1->id)->update([
            'created_at' => now()->subDays(3)->startOfDay(),
            'updated_at' => now()->subDays(3)->startOfDay(),
        ]);

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

        Cache::flush();

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

        $res->assertSee('data-role="platform-order-trend-7d"', false);
        $res->assertSee('data-role="platform-order-trend-7d-chart"', false);
        $res->assertSee('data-role="platform-order-trend-7d-meta"', false);
        $res->assertSee('近7天｜平台订单（按天）');

        // 断言日期行出现（只验证两个代表点）
        $res->assertSee($d3, false);
        $res->assertSee($d0, false);

        // 已付金额：PO_TREND_D3 10 元应进入 paid_sum
        $res->assertSee('¥10.00');
    }
}
