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

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

        $o1 = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_BATCH_MARK_0001',
            '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()->subMinutes(10),
            'paid_at' => now()->subMinutes(5),
            'meta' => [],
        ]);

        $o2 = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_BATCH_MARK_0002',
            '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()->subMinutes(9),
            'paid_at' => now()->subMinutes(4),
            'meta' => [],
        ]);

        // 不应被处理：未支付
        $o3 = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_BATCH_MARK_0003',
            '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,
            'placed_at' => now()->subMinutes(8),
            'meta' => [],
        ]);

        // scope=filtered 且要求 payment_status=paid + status=pending
        $this->post('/admin/platform-orders/batch-mark-activated', [
            'scope' => 'filtered',
            'payment_status' => 'paid',
            'status' => 'pending',
            'sync_status' => 'unsynced',
            'limit' => 50,
        ])->assertRedirect();

        $o1->refresh();
        $o2->refresh();
        $o3->refresh();

        $this->assertSame('activated', $o1->status);
        $this->assertSame('activated', $o2->status);
        $this->assertSame('pending', $o3->status);

        $audit1 = (array) (data_get($o1->meta, 'audit', []) ?? []);
        $this->assertNotEmpty($audit1);
        $last = end($audit1);
        $this->assertSame('batch_mark_activated', (string) data_get($last, 'action'));
        $this->assertNotEmpty(data_get($last, 'filters'));
        $this->assertNotEmpty(data_get($last, 'note'));
    }

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

        $this->post('/admin/platform-orders/batch-mark-activated', [
            'scope' => 'filtered',
            'payment_status' => 'paid',
            'status' => 'activated',
            'limit' => 50,
        ])->assertRedirect();
    }

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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'batch_mark_activated_sync_status_guard_plan',
            'name' => '批量生效 sync_status 安全阀测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $o1 = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_BATCH_MARK_SYNC_STATUS_GUARD_0001',
            '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()->subMinutes(10),
            'paid_at' => now()->subMinutes(5),
            'meta' => [],
        ]);

        // 故意不传 sync_status=unsynced（模拟旧入口/误操作）
        $this->post('/admin/platform-orders/batch-mark-activated', [
            'scope' => 'filtered',
            'payment_status' => 'paid',
            'status' => 'pending',
            'sync_status' => '',
            'limit' => 50,
        ])
            ->assertRedirect()
            ->assertSessionHas('warning');

        $o1->refresh();
        $this->assertSame('pending', $o1->status);
    }

    public function test_guest_cannot_batch_mark_activated(): void
    {
        $this->seed();

        $this->post('/admin/platform-orders/batch-mark-activated', [
            'scope' => 'filtered',
            'payment_status' => 'paid',
            'status' => 'pending',
            'limit' => 50,
        ])->assertRedirect('/admin/login');
    }
}
