<?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 AdminPlatformOrderClearBmpaErrorsShouldBlockWhenNotBmpaScopeTest extends TestCase
{
    use RefreshDatabase;

    protected function loginAsPlatformAdmin(): void
    {
        $this->seed();

        $this->post('/admin/login', [
            'email' => 'platform.admin@demo.local',
            'password' => 'Platform@123456',
        ])->assertRedirect('/admin');
    }

    protected function makeBmpaFailedOrder(string $orderNo, string $planCode): PlatformOrder
    {
        $merchant = Merchant::query()->firstOrFail();

        $plan = Plan::query()->create([
            'code' => $planCode,
            'name' => '清理BMPA失败标记阻断测试套餐：' . $planCode,
            'billing_cycle' => 'monthly',
            'price' => 1,
            'list_price' => 1,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        return PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => $orderNo,
            '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' => [
                'batch_mark_paid_and_activate_error' => [
                    'message' => '模拟 BMPA 失败',
                    'at' => now()->toDateTimeString(),
                    'admin_id' => 1,
                ],
            ],
        ]);
    }

    public function test_clear_bmpa_errors_filtered_should_block_when_syncable_only_is_set(): void
    {
        $this->loginAsPlatformAdmin();

        $order = $this->makeBmpaFailedOrder('PO_CLEAR_BMPA_CONFLICT_SYNCABLE_ONLY_0001', 'clear_bmpa_err_conflict_syncable_only_plan');

        $this->post('/admin/platform-orders/clear-bmpa-errors', [
            'scope' => 'filtered',
            'syncable_only' => '1',
        ])
            ->assertRedirect()
            ->assertSessionHas('warning');

        $order->refresh();
        $this->assertNotEmpty(data_get($order->meta, 'batch_mark_paid_and_activate_error.message'));
    }

    public function test_clear_bmpa_errors_filtered_should_block_when_only_sync_fail_filters_are_set(): void
    {
        $this->loginAsPlatformAdmin();

        $order = $this->makeBmpaFailedOrder('PO_CLEAR_BMPA_CONFLICT_SYNC_FAIL_FILTERS_0001', 'clear_bmpa_err_conflict_sync_fail_filters_plan');

        // 故意传入“同步失败”筛选（与 BMPA 清理不匹配）
        $this->post('/admin/platform-orders/clear-bmpa-errors', [
            'scope' => 'filtered',
            'fail_only' => '1',
        ])
            ->assertRedirect()
            ->assertSessionHas('warning');

        $order->refresh();
        $this->assertNotEmpty(data_get($order->meta, 'batch_mark_paid_and_activate_error.message'));
    }

    public function test_clear_bmpa_errors_filtered_should_block_when_sync_status_filter_is_present(): void
    {
        $this->loginAsPlatformAdmin();

        $order = $this->makeBmpaFailedOrder('PO_CLEAR_BMPA_CONFLICT_SYNC_STATUS_0001', 'clear_bmpa_err_conflict_sync_status_plan');

        // 即便锁定了 bmpa_failed_only，但叠加 sync_status 也应阻断（避免误清理/集合语义混乱）。
        $this->post('/admin/platform-orders/clear-bmpa-errors', [
            'scope' => 'filtered',
            'bmpa_failed_only' => '1',
            'sync_status' => 'failed',
        ])
            ->assertRedirect()
            ->assertSessionHas('warning');

        $order->refresh();
        $this->assertNotEmpty(data_get($order->meta, 'batch_mark_paid_and_activate_error.message'));
    }

    public function test_clear_bmpa_errors_filtered_should_block_when_synced_only_filter_is_present(): void
    {
        $this->loginAsPlatformAdmin();

        $order = $this->makeBmpaFailedOrder('PO_CLEAR_BMPA_CONFLICT_SYNCED_ONLY_0001', 'clear_bmpa_err_conflict_synced_only_plan');

        $this->post('/admin/platform-orders/clear-bmpa-errors', [
            'scope' => 'filtered',
            'bmpa_failed_only' => '1',
            'synced_only' => '1',
        ])
            ->assertRedirect()
            ->assertSessionHas('warning');

        $order->refresh();
        $this->assertNotEmpty(data_get($order->meta, 'batch_mark_paid_and_activate_error.message'));
    }

    public function test_clear_bmpa_errors_filtered_should_block_when_no_bmpa_scope_filters_are_set(): void
    {
        $this->loginAsPlatformAdmin();

        $order = $this->makeBmpaFailedOrder('PO_CLEAR_BMPA_BLOCK_NO_SCOPE_0001', 'clear_bmpa_err_block_no_scope_plan');

        $this->post('/admin/platform-orders/clear-bmpa-errors', [
            'scope' => 'filtered',
            // 故意不传 bmpa_failed_only/bmpa_error_keyword/batch_mark_paid_and_activate_24h
        ])
            ->assertRedirect()
            ->assertSessionHas('warning');

        $order->refresh();
        $this->assertNotEmpty(data_get($order->meta, 'batch_mark_paid_and_activate_error.message'));
    }
}
