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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'mark_paid_audit_snapshot_plan',
            'name' => '标记支付并生效审计快照测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 30,
            'list_price' => 30,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

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

        $this->post('/admin/platform-orders/' . $order->id . '/mark-paid-and-activate')
            ->assertRedirect();

        $order->refresh();

        $this->assertSame(30.0, (float) data_get($order->meta, 'audit.0.snapshot.paid_amount'));
        $this->assertSame(30.0, (float) data_get($order->meta, 'audit.0.snapshot.payable_amount'));

        $this->get('/admin/platform-orders/' . $order->id)
            ->assertOk()
            ->assertSee('paid=¥30.00')
            ->assertSee('payable_amount=30');
    }
}
