<?php

declare(strict_types=1);

use App\Models\User;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

beforeEach(function (): void {
    config()->set('app.url', 'http://skinbase26.test');
});

it('redirects a username subdomain root to the canonical profile URL', function () {
    User::factory()->create([
        'username' => 'gregor',
    ]);

    $response = app(Kernel::class)->handle(
        Request::create('/', 'GET', ['tab' => 'favourites'], [], [], ['HTTP_HOST' => 'gregor.skinbase26.test'])
    );

    expect($response->getStatusCode())->toBe(301);
    expect($response->headers->get('location'))->toBe('http://skinbase26.test/@gregor?tab=favourites');
});

it('redirects the legacy username subdomain gallery path to the canonical profile gallery URL', function () {
    User::factory()->create([
        'username' => 'gregor',
    ]);

    $response = app(Kernel::class)->handle(
        Request::create('/gallery', 'GET', [], [], [], ['HTTP_HOST' => 'gregor.skinbase26.test'])
    );

    expect($response->getStatusCode())->toBe(301);
    expect($response->headers->get('location'))->toBe('http://skinbase26.test/@gregor/gallery');
});

it('redirects an old username subdomain to the canonical profile URL for the renamed user', function () {
    $user = User::factory()->create([
        'username' => 'gregor',
    ]);

    DB::table('username_redirects')->insert([
        'old_username' => 'oldgregor',
        'new_username' => 'gregor',
        'user_id' => $user->id,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $response = app(Kernel::class)->handle(
        Request::create('/', 'GET', [], [], [], ['HTTP_HOST' => 'oldgregor.skinbase26.test'])
    );

    expect($response->getStatusCode())->toBe(301);
    expect($response->headers->get('location'))->toBe('http://skinbase26.test/@gregor');
});

it('does not treat reserved subdomains as profile hosts', function () {
    $this->call('GET', '/sections', [], [], [], ['HTTP_HOST' => 'www.skinbase26.test'])
        ->assertRedirect('/categories');
});
