#pragma once

#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QUrl>
#include <QUrlQuery>

/**
 * @brief Local HTTP server to receive OAuth2 authorization code callbacks.
 *
 * Listens on a configurable port (default 8080), intercepts the GET
 * request with the `?code=...` parameter, emits codeReceived(), and
 * returns a friendly HTML page to the browser.
 */
class OAuthCallbackServer : public QObject {
    Q_OBJECT

public:
    explicit OAuthCallbackServer(quint16 port = 8080, QObject *parent = nullptr);
    ~OAuthCallbackServer() override;

    /// Start listening. Returns false if the port is already in use.
    bool start();

    /// Stop listening and close any pending connection.
    void stop();

    /// The redirect URI clients should use (e.g. http://localhost:8080/callback)
    QString redirectUri() const;

    /// The port we are (or tried to be) listening on.
    quint16 port() const { return m_port; }

signals:
    /// Emitted when we successfully received an authorization code.
    void codeReceived(const QString &code, const QString &state);

    /// Emitted when the callback server encounters an error.
    void errorOccurred(const QString &errorMessage);

private slots:
    void onNewConnection();
    void onReadyRead();
    void onClientDisconnected();

private:
    void sendSuccessResponse(QTcpSocket *socket);
    void sendErrorResponse(QTcpSocket *socket, const QString &title, const QString &message);

    QTcpServer *m_server;
    QTcpSocket *m_clientSocket;
    quint16 m_port;
};