<?php

namespace Tests\Feature;

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

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

        $merchant = Merchant::query()->firstOrFail();

        $plan = Plan::query()->create([
            'code' => 'po_locked_sub_renew_flow_plan',
            'name' => '平台订单订阅锁定续费下单流转测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $sub = SiteSubscription::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'status' => 'active',
            'source' => 'manual',
            'subscription_no' => 'SS_LOCKED_RENEW_FLOW_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 10,
            'starts_at' => now(),
            'ends_at' => now()->addMonth(),
        ]);

        // 1) 订阅锁定的订单列表
        $indexUrl = '/admin/platform-orders?' . Arr::query([
            'site_subscription_id' => $sub->id,
        ]);
        $res = $this->get($indexUrl);
        $res->assertOk();
        $res->assertSee('为该订阅创建续费订单', false);

        // 去重降噪：中部订阅锁定区不应重复渲染该按钮（右上角主动作区已提供）
        $this->assertSame(1, substr_count((string) $res->getContent(), '为该订阅创建续费订单'));

        // 2) 点击一键续费下单（直接构造期望 create URL）
        $expectedCreateUrl = '/admin/platform-orders/create?' . Arr::query([
            'order_type' => 'renewal',
            'site_subscription_id' => $sub->id,
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'require_subscription' => '1',
            'quantity' => 1,
            'remark' => config('saasshop.platform_orders.renewal_order_remark_prefix', '来自订阅：') . $sub->subscription_no,
            'back' => $indexUrl,
        ]);

        $res->assertSee($expectedCreateUrl, false);

        $res2 = $this->get($expectedCreateUrl);
        $res2->assertOk();
        $res2->assertSee('新建平台订单', false);
        $res2->assertSee('该订单类型为「续费」', false);

        // 3) 提交创建订单：应携带 back 并最终落在订单详情页，且详情页可返回到锁定列表
        $postRes = $this->post('/admin/platform-orders', [
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => $sub->id,
            'order_type' => 'renewal',
            'quantity' => 1,
            'discount_amount' => 0,
            'payment_channel' => 'offline',
            'remark' => 'test-renew-remark',
            'back' => $indexUrl,
        ]);

        $order = PlatformOrder::query()->latest('id')->firstOrFail();

        $expectedRedirect = '/admin/platform-orders/' . $order->id . '?' . Arr::query([
            'back' => $indexUrl,
        ]);

        $postRes->assertRedirect($expectedRedirect);

        $showRes = $this->get($expectedRedirect);
        $showRes->assertOk();
        $showRes->assertSee('← 返回上一页（保留上下文）', false);
        $showRes->assertSee('href="' . $indexUrl . '"', false);
    }
}
