<?php

namespace Tests\Feature;

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

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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'sub_show_to_po_create_end2end_plan',
            'name' => '订阅详情->创建续费订单 end2end 测试套餐',
            '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_END2END_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) 从订阅详情页进入
        $subShow = $this->get('/admin/site-subscriptions/' . $sub->id);
        $subShow->assertOk();

        // 订阅详情页的“创建续费订单”链接 back 应该回到订阅详情自身
        $expectedBack = '/admin/site-subscriptions/' . $sub->id;
        $subShow->assertSee('back=' . urlencode($expectedBack), false);
        $subShow->assertSee('order_type=renewal', false);
        $subShow->assertSee('require_subscription=1', false);

        // 2) 打开创建页（携带默认值 + back）
        $createUrl = '/admin/platform-orders/create?'
            . 'merchant_id=' . $merchant->id
            . '&plan_id=' . $plan->id
            . '&site_subscription_id=' . $sub->id
            . '&order_type=renewal'
            . '&require_subscription=1'
            . '&quantity=1'
            . '&remark=' . urlencode('来自订阅：' . $sub->subscription_no)
            . '&back=' . urlencode($expectedBack);

        $createRes = $this->get($createUrl);
        $createRes->assertOk();
        $createRes->assertSee('name="back"', false);
        $createRes->assertSee('value="' . $expectedBack . '"', false);
        $createRes->assertSee('value="' . $sub->id . '"', false);

        // 3) 提交创建订单，断言 redirect 到 show 且带回 back
        $storeRes = $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' => '来自订阅：' . $sub->subscription_no,
            'back' => $expectedBack,
        ]);

        $storeRes->assertRedirect();
        $location = (string) $storeRes->headers->get('Location');
        $this->assertStringContainsString('/admin/platform-orders/', $location);
        $this->assertStringContainsString('back=' . urlencode($expectedBack), $location);

        // 4) 打开 show 页，确认“返回上一页（保留上下文）”存在
        $showRes = $this->get($location);
        $showRes->assertOk();
        $showRes->assertSee('← 返回上一页（保留上下文）');
        $showRes->assertSee('href="' . $expectedBack . '"', false);
    }
}
