<?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 AdminSiteSubscriptionShowTest extends TestCase
{
    use RefreshDatabase;

    protected function seedSubscriptionForShow(): array
    {
        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'sub_show_test',
            'name' => '订阅详情测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 88,
            'list_price' => 88,
            '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_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => 'monthly',
            'period_months' => 1,
            'amount' => 88,
            'starts_at' => now()->subDays(2),
            'ends_at' => now()->addDays(20),
            'activated_at' => now()->subDays(2),
        ]);

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => $sub->id,
            'created_by_admin_id' => 1,
            'order_no' => 'PO_SUB_SHOW_0001',
            'order_type' => 'subscription',
            'status' => 'activated',
            'payment_status' => 'paid',
            'plan_name' => $plan->name,
            'billing_cycle' => 'monthly',
            'period_months' => 1,
            'quantity' => 1,
            'list_amount' => 88,
            'discount_amount' => 0,
            'payable_amount' => 88,
            'paid_amount' => 88,
            'placed_at' => now()->subDay(),
            'paid_at' => now()->subDay(),
            'activated_at' => now()->subDay(),
            'meta' => [
                'subscription_activation' => [
                    'subscription_id' => $sub->id,
                    'synced_at' => now()->subDay()->toDateTimeString(),
                    'admin_id' => 1,
                ],
                // 订阅维度治理摘要：回执/退款汇总口径应可识别 summary
                'payment_summary' => [
                    'count' => 1,
                    'total_amount' => 88,
                    'last_at' => now()->subDay()->toDateTimeString(),
                    'last_amount' => 88,
                    'last_channel' => 'bank_transfer',
                ],
                'refund_summary' => [
                    'count' => 1,
                    'total_amount' => 10,
                    'last_at' => now()->subHours(12)->toDateTimeString(),
                    'last_amount' => 10,
                    'last_channel' => 'bank_transfer',
                ],
                'subscription_activation_error' => [
                    'message' => '模拟失败：站点已过期',
                    'at' => now()->toDateTimeString(),
                    'admin_id' => 1,
                ],
            ],
        ]);

        return [$merchant, $plan, $sub];
    }

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

        [$merchant, $plan, $sub] = $this->seedSubscriptionForShow();

        $this->get('/admin/site-subscriptions/' . $sub->id)
            ->assertOk()
            ->assertSee('订阅详情')
            ->assertSee('SUB_SHOW_0001')
            ->assertSee('关联订单总数')
            ->assertSee('/admin/platform-orders?site_subscription_id=' . $sub->id, false)
            ->assertSee('可同步（已支付+已生效+未同步）')
            ->assertSee('未同步（无记录）')
            ->assertSee('失败原因Top3')
            ->assertSee('/admin/platform-orders?site_subscription_id=' . $sub->id . '&sync_status=failed&sync_error_keyword=' . urlencode('模拟失败：站点已过期'), false)
            ->assertSee('/admin/platform-orders?site_subscription_id=' . $sub->id . '&sync_status=synced', false)
            ->assertSee('/admin/platform-orders?site_subscription_id=' . $sub->id . '&sync_status=failed', false)
            ->assertSee('/admin/platform-orders?site_subscription_id=' . $sub->id . '&syncable_only=1', false)
            ->assertSee('/admin/platform-orders?site_subscription_id=' . $sub->id . '&sync_status=unsynced', false)
            ->assertSee('有回执订单 / 回执总额')
            ->assertSee('/admin/platform-orders?site_subscription_id=' . $sub->id . '&receipt_status=has', false)
            ->assertSee('/admin/platform-orders?site_subscription_id=' . $sub->id . '&receipt_status=none', false)
            ->assertSee('有退款订单 / 退款总额')
            ->assertSee('/admin/platform-orders?site_subscription_id=' . $sub->id . '&refund_status=has', false)
            ->assertSee('/admin/platform-orders?site_subscription_id=' . $sub->id . '&refund_status=none', false)
            ->assertSee('/admin/platform-orders?site_subscription_id=' . $sub->id . '&refund_inconsistent=1', false)
            ->assertSee('对账差额（回执-已付）')
            ->assertSee('/admin/platform-orders?site_subscription_id=' . $sub->id . '&reconcile_mismatch=1', false)
            ->assertSee('对账不一致订单：')
            ->assertSee('关联平台订单')
            ->assertSee('PO_SUB_SHOW_0001')
            ->assertSee('同步时间')
            ->assertSee('失败原因')
            ->assertSee('在平台订单页打开')
            ->assertSee('/admin/platform-orders/create?merchant_id=' . $merchant->id . '&plan_id=' . $plan->id . '&site_subscription_id=' . $sub->id . '&order_type=renewal&require_subscription=1', false);
    }

    public function test_guest_cannot_open_site_subscription_show_page(): void
    {
        $merchant = Merchant::query()->create([
            'name' => '访客测试站点',
            'slug' => 'guest-test',
            'status' => 'active',
        ]);

        $sub = SiteSubscription::query()->create([
            'merchant_id' => $merchant->id,
            'status' => 'activated',
            'source' => 'manual',
            'subscription_no' => 'SUB_GUEST_0001',
            'plan_name' => '访客测试套餐',
            'billing_cycle' => 'monthly',
            'period_months' => 1,
            'amount' => 88,
            'starts_at' => now()->subDay(),
            'ends_at' => now()->addDays(29),
            'activated_at' => now()->subDay(),
        ]);

        $this->get('/admin/site-subscriptions/' . $sub->id)
            ->assertRedirect('/admin/login');
    }
}
