<?php

namespace Tests\Feature;

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

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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'created_at_range_test',
            'name' => '创建时间范围筛选测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $in = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_CREATED_RANGE_IN',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 0,
        ]);

        $out = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_CREATED_RANGE_OUT',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 0,
        ]);

        // 强制调整 created_at 到不同日期
        PlatformOrder::query()->where('id', $in->id)->update([
            'created_at' => now()->subDays(2)->startOfDay(),
            'updated_at' => now()->subDays(2)->startOfDay(),
        ]);
        PlatformOrder::query()->where('id', $out->id)->update([
            'created_at' => now()->subDays(10)->startOfDay(),
            'updated_at' => now()->subDays(10)->startOfDay(),
        ]);

        $from = now()->subDays(3)->format('Y-m-d');
        $to = now()->subDays(1)->format('Y-m-d');

        $this->get('/admin/platform-orders?created_from=' . $from . '&created_to=' . $to)
            ->assertOk()
            ->assertSee('PO_CREATED_RANGE_IN')
            ->assertDontSee('PO_CREATED_RANGE_OUT');
    }
}
