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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'mark_refund_status_back_test_plan',
            'name' => '退款状态回退治理测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_MARK_REFUND_BACK_0001',
            'order_type' => 'new_purchase',
            'status' => 'activated',
            'payment_status' => 'refunded',
            '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(),
            'refunded_at' => now(),
            'meta' => [
                'refund_summary' => [
                    'count' => 1,
                    'total_amount' => 1.00,
                ],
            ],
        ]);

        // 回退到部分退款
        $this->post('/admin/platform-orders/' . $order->id . '/mark-partially-refunded')
            ->assertRedirect();
        $order->refresh();
        $this->assertSame('partially_refunded', $order->payment_status);
        $this->assertSame('mark_partially_refunded', (string) data_get($order->meta, 'audit.0.action'));

        // 再回退到已支付
        $this->post('/admin/platform-orders/' . $order->id . '/mark-paid-status')
            ->assertRedirect();
        $order->refresh();
        $this->assertSame('paid', $order->payment_status);
        $this->assertSame('mark_paid_status', (string) data_get($order->meta, 'audit.1.action'));
    }
}
