<?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 Tests\TestCase;

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

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

        $plan = Plan::query()->create([
            'code' => 'link_test_monthly',
            'name' => '联动测试（月付）',
            'billing_cycle' => 'monthly',
            'price' => 9.9,
            'list_price' => 9.9,
            'status' => 'active',
            'sort' => 1,
            'published_at' => now(),
        ]);

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

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => $sub->id,
            'order_no' => 'PO_LINK_PLAN_0001',
            'order_type' => 'new_purchase',
            'status' => 'activated',
            'payment_status' => 'paid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'list_amount' => 9.9,
            'discount_amount' => 0,
            'payable_amount' => 9.9,
            'paid_amount' => 9.9,
            'placed_at' => now()->subHour(),
            'paid_at' => now()->subMinutes(30),
            'activated_at' => now()->subMinutes(20),
        ]);

        $this->get('/admin/plans')
            ->assertOk()
            ->assertSee('/admin/site-subscriptions?plan_id=' . $plan->id, false)
            ->assertSee('/admin/platform-orders?plan_id=' . $plan->id, false)
            ->assertSee('关联订阅')
            ->assertSee('关联平台订单');
    }
}
