<?php

namespace Tests\Feature;

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

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

        $plan = Plan::query()->create([
            'code' => 'publish_toggle_test',
            'name' => '发布状态切换测试',
            'billing_cycle' => 'monthly',
            'price' => 9,
            'list_price' => 9,
            'status' => 'draft',
            'sort' => 10,
            'published_at' => null,
        ]);

        $this->post('/admin/plans/' . $plan->id . '/set-published', [
            'published' => '1',
        ])->assertRedirect();

        $plan->refresh();
        $this->assertNotNull($plan->published_at);

        $this->post('/admin/plans/' . $plan->id . '/set-published', [
            'published' => '0',
        ])->assertRedirect();

        $plan->refresh();
        $this->assertNull($plan->published_at);
    }

    public function test_guest_cannot_set_plan_published_flag(): void
    {
        $this->seed();

        $plan = Plan::query()->create([
            'code' => 'publish_toggle_guest_test',
            'name' => '发布状态切换测试(guest)',
            'billing_cycle' => 'monthly',
            'price' => 9,
            'list_price' => 9,
            'status' => 'draft',
            'sort' => 10,
            'published_at' => null,
        ]);

        $this->post('/admin/plans/' . $plan->id . '/set-published', [
            'published' => '1',
        ])->assertRedirect('/admin/login');
    }
}
