<?php

namespace Tests\Feature;

use App\Models\Merchant;
use App\Models\Plan;
use App\Models\PlatformOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Arr;
use Tests\TestCase;

class AdminPlatformOrderAddPaymentReceiptShouldRedirectBackToShowWithAnchorAndBackTest 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_add_payment_receipt_should_redirect_to_show_with_back_and_payment_anchor(): void
    {
        $this->loginAsPlatformAdmin();

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'add_payment_receipt_redirect_back_anchor_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_ADD_PAYMENT_RECEIPT_REDIRECT_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(),
        ]);

        $back = '/admin/platform-orders?reconcile_mismatch=1';

        $res = $this->post('/admin/platform-orders/' . $order->id . '/add-payment-receipt', [
            'type' => 'bank_transfer',
            'channel' => 'icbc',
            'amount' => 30,
            'paid_at' => now()->format('Y-m-d H:i:s'),
            'note' => '测试回执',
            'back' => $back,
        ]);

        $expected = '/admin/platform-orders/' . $order->id . '?' . Arr::query([
            'back' => $back,
        ]) . '#add-payment-receipt';

        $res->assertRedirect($expected);
    }
}
