<?php

namespace Tests\Feature;

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

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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'sub_show_to_create_po_back_flow_plan',
            'name' => '订阅详情->创建平台订单 back 流程测试套餐',
            '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' => 'activated',
            'source' => 'manual',
            'subscription_no' => 'SUB_SHOW_TO_CREATE_PO_BACK_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 10,
            'starts_at' => now()->subDay(),
            'ends_at' => now()->addMonth(),
            'activated_at' => now()->subDay(),
        ]);

        // 1) 订阅详情页存在“创建续费订单”链接（带 back 回到订阅详情）
        $res = $this->get('/admin/site-subscriptions/' . $sub->id);
        $res->assertOk();

        $expectedCreateUrl = '/admin/platform-orders/create?' . Arr::query([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => $sub->id,
            'order_type' => 'renewal',
            'require_subscription' => '1',
            'quantity' => 1,
            'remark' => '来自订阅：' . $sub->subscription_no,
            'back' => '/admin/site-subscriptions/' . $sub->id,
        ]);
        $res->assertSee($expectedCreateUrl, false);

        // 2) 打开 create 页面，默认值应回显
        $createRes = $this->get($expectedCreateUrl);
        $createRes->assertOk();
        $createRes->assertSee('value="' . $merchant->id . '"', false);
        $createRes->assertSee('value="' . $plan->id . '"', false);
        $createRes->assertSee('value="' . $sub->id . '"', false);
        $createRes->assertSee('value="renewal"', false);

        // 3) 提交 store，应该 redirect 到订单详情并携带 back
        $storeRes = $this->post('/admin/platform-orders', [
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => $sub->id,
            'order_type' => 'renewal',
            'require_subscription' => '1',
            'quantity' => 1,
            'discount_amount' => 0,
            'payment_channel' => '',
            'remark' => '来自订阅：' . $sub->subscription_no,
            'back' => '/admin/site-subscriptions/' . $sub->id,
        ]);

        $storeRes->assertRedirect();
        $location = (string) $storeRes->headers->get('Location');
        $this->assertStringContainsString('/admin/platform-orders/', $location);
        $this->assertStringContainsString('back=%2Fadmin%2Fsite-subscriptions%2F' . $sub->id, $location);

        // 4) 打开订单详情页：应展示“返回上一页”按钮（safe back）
        $showRes = $this->get($location);
        $showRes->assertOk();
        $showRes->assertSee('← 返回上一页（保留上下文）', false);
        $showRes->assertSee('/admin/site-subscriptions/' . $sub->id, false);
    }
}
