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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'batch_mark_activated_filter_fields_plan',
            'name' => '批量生效（筛选字段）测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        // A：无回执（广义） + 对账不一致（回执总额 0，但 paid_amount=10）=> reconcile_mismatch=1 命中
        $a = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_BMA_FILTER_A',
            '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' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'paid_at' => now(),
            'meta' => [],
        ]);

        // B：有回执（summary=10）+ 对账一致 => reconcile_mismatch=1 不应命中
        $b = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_BMA_FILTER_B',
            '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' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'paid_at' => now(),
            'meta' => [
                'payment_summary' => [
                    'total_amount' => 10.00,
                    'count' => 1,
                ],
            ],
        ]);

        // C：有退款（refund_summary=1）+ 无回执（广义） + 对账不一致（回执总额0，但 paid_amount=10）
        // 如果不加 refund_status=none 的筛选，会被误推进；这里用测试保证“退款筛选口径”能影响批量动作
        $c = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_BMA_FILTER_C',
            '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' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'paid_at' => now(),
            'meta' => [
                'refund_summary' => [
                    'count' => 1,
                    'total_amount' => 1.00,
                ],
            ],
        ]);

        // 治理口径升级：当筛选命中「无回执（广义）/对账不一致」等治理集合时，不允许直接批量仅标记为已生效。
        // 这里用测试锁定：应直接被阻断，并给出 warning；订单状态不应发生变化。
        $this->post('/admin/platform-orders/batch-mark-activated', [
            'scope' => 'filtered',
            'payment_status' => 'paid',
            'status' => 'pending',
            'sync_status' => 'unsynced',
            'receipt_status' => 'none',
            'refund_status' => 'none',
            'reconcile_mismatch' => '1',
            'limit' => 50,
        ])
            ->assertRedirect()
            ->assertSessionHas('warning', function ($msg) {
                $msg = (string) $msg;
                return str_contains($msg, '无回执（广义）') || str_contains($msg, '回执');
            });

        $a->refresh();
        $b->refresh();
        $c->refresh();

        $this->assertSame('pending', $a->status);
        $this->assertSame('pending', $b->status);
        $this->assertSame('pending', $c->status);
    }
}
