<?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 AdminPlatformOrderClearSyncErrorsReconcileMismatchFilterFieldsTest 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_clear_sync_errors_filtered_scope_respects_reconcile_mismatch_filter_fields(): void
    {
        $this->loginAsPlatformAdmin();

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'clear_sync_errors_reconcile_mismatch_filter_fields_test',
            'name' => '清理失败标记对账不一致筛选字段测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_CLEAR_SYNC_ERRORS_RECON_MISMATCH_0001',
            'order_type' => 'new_purchase',
            'status' => 'activated',
            'payment_status' => 'paid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'paid_at' => now(),
            'activated_at' => now(),
            'meta' => [
                'subscription_activation_error' => [
                    'message' => '模拟失败原因',
                    'at' => now()->toDateTimeString(),
                    'admin_id' => 1,
                ],
                'payment_summary' => [
                    'count' => 1,
                    'total_amount' => 9.98,
                ],
            ],
        ]);

        // 确认列表页清理表单透传 reconcile_mismatch
        $page = $this->get('/admin/platform-orders?reconcile_mismatch=1');
        $page->assertOk();
        $page->assertSee('name="reconcile_mismatch"', false);
        $page->assertSee('value="1"', false);

        $res = $this->post('/admin/platform-orders/clear-sync-errors', [
            'scope' => 'filtered',
            'reconcile_mismatch' => '1',
        ]);
        $res->assertRedirect();

        $order->refresh();
        $this->assertEmpty(data_get($order->meta, 'subscription_activation_error'));
    }
}
