<?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 AdminPlatformOrderIndexBatchButtonsShouldEnableWhenFiltersMatchTest 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 assertButtonEnabled(string $html, string $label): void
    {
        $this->assertStringContainsString($label, $html);

        $pattern = '/' . preg_quote('<button', '/') . '[^>]*>' . preg_quote($label, '/') . preg_quote('</button>', '/') . '/u';
        $this->assertTrue((bool) preg_match($pattern, $html, $m), '未找到按钮：' . $label);

        $btnHtml = (string) ($m[0] ?? '');
        $this->assertFalse(str_contains($btnHtml, 'disabled'), '按钮不应被禁用：' . $label);
    }

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

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

        // 已支付+已生效+有回执，理论上属于“可同步”集合（即使未真正 syncable_only 过滤命中，这里只测按钮状态）
        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_IDX_BTN_ENABLE_SYNC_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' => [
                'payment_summary' => ['count' => 1, 'total_amount' => 10],
            ],
        ]);

        $res = $this->get('/admin/platform-orders?syncable_only=1&receipt_status=has');
        $res->assertOk();

        $html = (string) $res->getContent();

        $this->assertButtonEnabled($html, '批量同步订阅（当前筛选范围）');
        $this->assertStringNotContainsString('data-role="batch-activate-subscriptions-blocked-hint"', $html);
    }

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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'po_idx_batch_btn_enable_bmpa_plan',
            'name' => '批量BMPA按钮可用性测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_IDX_BTN_ENABLE_BMPA_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' => 10,
            'paid_amount' => 0,
            'placed_at' => now(),
            'meta' => [],
        ]);

        $res = $this->get('/admin/platform-orders?status=pending&payment_status=unpaid');
        $res->assertOk();

        $html = (string) $res->getContent();

        $this->assertButtonEnabled($html, '批量标记支付并生效（含订阅同步）（当前筛选范围）');
        $this->assertStringNotContainsString('data-role="batch-bmpa-blocked-hint"', $html);
    }

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

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

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

        $res = $this->get('/admin/platform-orders?status=pending&payment_status=paid&sync_status=unsynced');
        $res->assertOk();

        $html = (string) $res->getContent();

        $this->assertButtonEnabled($html, '批量仅标记为已生效（当前筛选范围）');
        $this->assertStringNotContainsString('data-role="batch-mark-activated-blocked-hint"', $html);
    }
}
