<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Pipeline\Pipeline;
use Laravel\Fortify\Contracts\LoginResponse;
use Laravel\Fortify\Http\Requests\LoginRequest;

class CustomAuthenticatedSessionController
{
    public function store(LoginRequest $request): LoginResponse
    {
        return $this->loginPipeline($request)->then(function ($request) {
            // Skip session regeneration in Docker environment to avoid session persistence issues
            if (!env('IS_DOCKER', false)) {
                $request->session()->regenerate();
            }

            return app(LoginResponse::class);
        });
    }

    protected function loginPipeline(LoginRequest $request)
    {
        if (method_exists($this, 'fortify')) {
            return $this->fortify()->loginPipeline($request);
        }

        return (new Pipeline(app()))->send($request)->through(array_filter([
            config('fortify.limiters.login') ? null : \Laravel\Fortify\Actions\EnsureLoginIsNotThrottled::class,
            config('fortify.lowercase_usernames') ? \Laravel\Fortify\Actions\CanonicalizeUsername::class : null,
            \Laravel\Fortify\Actions\AttemptToAuthenticate::class,
            // Skip PrepareAuthenticatedSession in Docker as it calls session()->migrate() which causes issues
            env('IS_DOCKER', false) ? null : \Laravel\Fortify\Actions\PrepareAuthenticatedSession::class,
        ]));
    }
}
