<?php

namespace Tests\Feature;

use App\Models\Subscription;
use App\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class RegisterClinicTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed();
    }

    protected function payload(array $overrides = []): array
    {
        return array_merge([
            'clinic_name' => 'Smile Dental',
            'slug' => 'smile-dental',
            'name' => 'Dr. Ahmed',
            'email' => 'ahmed@example.com',
            'phone' => '+9647701234567',
            'password' => 'password123',
            'password_confirmation' => 'password123',
            'locale' => 'ar',
            'terms' => '1',
        ], $overrides);
    }

    public function test_signup_creates_tenant_owner_and_trial(): void
    {
        $central = 'http://'.config('tenancy.central_domain');

        $response = $this->post($central.'/register', $this->payload());

        $tenant = Tenant::where('slug', 'smile-dental')->firstOrFail();
        $response->assertRedirect($tenant->url('/dashboard'));

        $this->assertSame('trial', $tenant->status);

        $owner = $tenant->users()->firstOrFail();
        $this->assertTrue($owner->hasRole('clinic_owner'));

        $subscription = Subscription::where('tenant_id', $tenant->id)->firstOrFail();
        $this->assertSame('trialing', $subscription->status);
        $this->assertTrue($subscription->isActive());
        $this->assertEqualsWithDelta(
            now()->addDays(14)->timestamp,
            $subscription->current_period_ends_at->timestamp,
            5
        );
    }

    public function test_reserved_and_duplicate_slugs_are_rejected(): void
    {
        $central = 'http://'.config('tenancy.central_domain');

        $this->post($central.'/register', $this->payload(['slug' => 'admin']))
            ->assertSessionHasErrors('slug');

        $this->post($central.'/register', $this->payload());
        $this->post($central.'/register', $this->payload([
            'email' => 'other@example.com',
        ]))->assertSessionHasErrors('slug');
    }
}
