{% skip_file if flag?(:api_only) %}

module Invidious::Routes::Login
    def self.login_page(env)
        locale = env.get("preferences").as(Preferences).locale

        user = env.get? "user"
        referer = get_referer(env, "/feed/subscriptions")
        return env.redirect referer if user
        return error_template(400, "Login has been disabled by administrator.") if !CONFIG.login_enabled
        

        if forwarded_user = env.request.headers["X-authentik-email"]? 
            begin
                email = forwarded_user.try &.downcase.byte_slice(0, 254)
                
                return error_template(401, "User ID is a required field") if email.nil? || email.empty?
                
                user = Invidious::Database::Users.select(email: email)
                if user
                    sid = Base64.urlsafe_encode(Random::Secure.random_bytes(32))
                    Invidious::Database::SessionIDs.insert(sid, email)
                    env.response.cookies["SID"] = Invidious::User::Cookies.sid(CONFIG.domain, sid)

                    if env.request.cookies["PREFS"]?
                        cookie = env.request.cookies["PREFS"]
                        cookie.expires = Time.utc(1990, 1, 1)
                        env.response.cookies << cookie
                    end
                else
                    return error_template(400, "Registration has been disabled by administrator.") if !CONFIG.registration_enabled

                    sid = Base64.urlsafe_encode(Random::Secure.random_bytes(32))
                    user, sid = create_user(sid, email, "")

                    if language_header = env.request.headers["Accept-Language"]?
                        if language = ANG.language_negotiator.best(language_header, LOCALES.keys)
                            user.preferences.locale = language.header
                        end
                    end

                    Invidious::Database::Users.insert(user)
                    Invidious::Database::SessionIDs.insert(sid, email)

                    view_name = "subscriptions_#{sha256(user.email)}"
                    PG_DB.exec("CREATE MATERIALIZED VIEW #{view_name} AS #{MATERIALIZED_VIEW_SQL.call(user.email)}")
                    env.response.cookies["SID"] = Invidious::User::Cookies.sid(CONFIG.domain, sid)

                    if env.request.cookies["PREFS"]?
                        user.preferences = env.get("preferences").as(Preferences)
                        Invidious::Database::Users.update_preferences(user)

                        cookie = env.request.cookies["PREFS"]
                        cookie.expires = Time.utc(1990, 1, 1)
                        env.response.cookies << cookie
                    end
                end

                return env.redirect referer
            rescue ex
                return error_template(500, "Authentication error: #{ex.message}")
            end
        end
        env.redirect referer
    end

    def self.login(env)
        referer = get_referer(env, "/feed/subscriptions")
        env.redirect referer
        return error_template(403, "Login post is not supported.")
    end

    def self.signout(env)
        locale = env.get("preferences").as(Preferences).locale

        user = env.get? "user"
        sid = env.get? "sid"
        referer = get_referer(env)

        return env.redirect referer if !user

        user = user.as(User)
        sid = sid.as(String)
        token = env.params.body["csrf_token"]?

        begin
            validate_request(token, sid, env.request, HMAC_KEY, locale)
        rescue ex
            return error_template(400, ex)
        end

        Invidious::Database::SessionIDs.delete(sid: sid)

        env.request.cookies.each do |cookie|
            cookie.expires = Time.utc(1990, 1, 1)
            env.response.cookies << cookie
        end

        env.redirect referer
    end
end