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

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

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

        $order->refresh();

        $refunds = (array) data_get($order->meta, 'refund_receipts', []);
        $this->assertCount(1, $refunds);
        $this->assertSame('refund', data_get($refunds[0], 'type'));
        $this->assertSame('alipay', data_get($refunds[0], 'channel'));
        $this->assertSame(10.0, (float) data_get($refunds[0], 'amount'));

        $this->assertSame('partially_refunded', $order->payment_status);
        $this->assertNotNull($order->refunded_at);

        // 确保退款轨迹可用于对账统计
        $totalRefunded = 0.0;
        foreach ($refunds as $r) {
            $totalRefunded += (float) (data_get($r, 'amount') ?? 0);
        }
        $this->assertSame(10.0, $totalRefunded);
    }

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

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

        $this->post('/admin/platform-orders/' . $order->id . '/add-refund-receipt', [
            'type' => 'refund',
            'channel' => 'wechat',
            'amount' => 30,
            'refunded_at' => now()->format('Y-m-d H:i:s'),
            'note' => '全额退款',
        ])->assertRedirect();

        $order->refresh();
        $this->assertSame('refunded', $order->payment_status);
        $this->assertNotNull($order->refunded_at);

        $refunds = (array) data_get($order->meta, 'refund_receipts', []);
        $this->assertCount(1, $refunds);
    }

    public function test_guest_cannot_add_refund_receipt(): void
    {
        $this->seed();

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

        $this->post('/admin/platform-orders/' . $order->id . '/add-refund-receipt', [
            'type' => 'refund',
            'amount' => 10,
        ])->assertRedirect('/admin/login');
    }
}
