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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'add_refund_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_REFUND_RECEIPT_REDIRECT_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' => 30,
            'paid_amount' => 30,
            'placed_at' => now(),
            'paid_at' => now(),
            'activated_at' => now(),
        ]);

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

        $res = $this->post('/admin/platform-orders/' . $order->id . '/add-refund-receipt', [
            'type' => 'refund',
            'channel' => 'icbc',
            'amount' => 10,
            'refunded_at' => now()->format('Y-m-d H:i:s'),
            'note' => '测试退款',
            'back' => $back,
        ]);

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

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