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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'clear_sync_err_filtered_test',
            'name' => '清理失败标记（范围）测试',
            'billing_cycle' => 'monthly',
            'price' => 1,
            'list_price' => 1,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $failedA = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_CLEAR_ERR_F_0001',
            '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' => 1,
            'paid_amount' => 0,
            'placed_at' => now(),
            'meta' => [
                'subscription_activation_error' => [
                    'message' => '模拟失败A',
                    'at' => now()->toDateTimeString(),
                    'admin_id' => 1,
                ],
            ],
        ]);

        $failedB = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_CLEAR_ERR_F_0002',
            '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' => 1,
            'paid_amount' => 1,
            'placed_at' => now(),
            'meta' => [
                'subscription_activation_error' => [
                    'message' => '模拟失败B',
                    'at' => now()->toDateTimeString(),
                    'admin_id' => 1,
                ],
            ],
        ]);

        $failedRefunded = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_CLEAR_ERR_F_REFUNDED',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'paid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 1,
            'paid_amount' => 1,
            'placed_at' => now(),
            'meta' => [
                'refund_summary' => [
                    'count' => 1,
                    'total_amount' => 0.50,
                ],
                'subscription_activation_error' => [
                    'message' => '模拟失败REFUNDED',
                    'at' => now()->toDateTimeString(),
                    'admin_id' => 1,
                ],
            ],
        ]);

        // 仅清理“status=pending + refund_status=none”范围内的失败标记：应该只清掉 failedA（不应清掉 failedRefunded）
        $this->post('/admin/platform-orders/clear-sync-errors', [
            'scope' => 'filtered',
            'status' => 'pending',
            'refund_status' => 'none',
        ])->assertRedirect();

        // 增加一条带 subscription_id 的失败订单，用于验证 site_subscription_id 精确过滤生效
        $sub = \App\Models\SiteSubscription::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'status' => 'activated',
            'source' => 'manual',
            'subscription_no' => 'SUB_CLEAR_ERR_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 1,
            'starts_at' => now()->subDay(),
            'ends_at' => now()->addMonth(),
            'activated_at' => now()->subDay(),
        ]);

        $failedWithSub = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => $sub->id,
            'order_no' => 'PO_CLEAR_ERR_SUB_0001',
            'order_type' => 'renewal',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 1,
            'paid_amount' => 0,
            'placed_at' => now(),
            'meta' => [
                'subscription_activation_error' => [
                    'message' => '模拟失败SUB',
                    'at' => now()->toDateTimeString(),
                    'admin_id' => 1,
                ],
            ],
        ]);

        // 仅清理指定订阅ID范围内的失败标记：只清掉 failedWithSub
        $this->post('/admin/platform-orders/clear-sync-errors', [
            'scope' => 'filtered',
            'site_subscription_id' => (string) $sub->id,
        ])->assertRedirect();

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

        $failedA->refresh();
        $failedB->refresh();
        $failedRefunded->refresh();

        $this->assertEmpty(data_get($failedA->meta, 'subscription_activation_error'));
        $this->assertNotEmpty(data_get($failedA->meta, 'audit.0.action'));
        $this->assertSame('clear_sync_error', data_get($failedA->meta, 'audit.0.action'));

        $this->assertNotEmpty(data_get($failedB->meta, 'subscription_activation_error.message'));

        // 有退款的失败订单不应被 refund_status=none 的清理动作误命中
        $this->assertNotEmpty(data_get($failedRefunded->meta, 'subscription_activation_error.message'));
    }
}
