import { d as defineEventHandler, j as getQuery, c as createError, aQ as useRuntimeConfig, G as createContentManager, du as generateJWT } from '../../../../nitro/nitro.mjs';
import { i as isValidProvider, e as exchangeCodeForToken, g as getOAuthUserInfo } from '../../../../_/oauth.mjs';
import 'node:crypto';
import 'jsonwebtoken';
import 'node:fs';
import 'node:module';
import 'node:path';
import 'node:url';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'pino';
import 'drizzle-orm/better-sqlite3';
import 'drizzle-orm/node-postgres';
import 'drizzle-orm/mysql2';
import 'better-sqlite3';
import 'pg';
import 'mysql2/promise';
import 'drizzle-orm';
import 'fs';
import 'path';
import 'prom-client';
import 'bcryptjs';
import '@node-rs/argon2';
import 'node:async_hooks';
import 'crypto';
import 'node:dns';
import 'node:util';
import 'node:net';
import 'fs/promises';
import 'url';
import 'semver';

const callback_get = defineEventHandler(async (event) => {
  var _a, _b;
  try {
    const provider = (_a = event.context.params) == null ? void 0 : _a.provider;
    const query = getQuery(event);
    const code = query.code;
    if (!provider || !isValidProvider(provider)) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Invalid OAuth provider"
      });
    }
    if (query.error) {
      throw createError({
        statusCode: 400,
        statusMessage: "OAuth Error",
        message: `OAuth provider returned error: ${query.error}`
      });
    }
    if (!code) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Authorization code is missing"
      });
    }
    const config = useRuntimeConfig();
    const apiBase = config.public.apiBase || "http://localhost:2102";
    const callbackUrl = `${apiBase}/api/auth/${provider}/callback`;
    const accessToken = await exchangeCodeForToken(provider, code, callbackUrl);
    const oauthUser = await getOAuthUserInfo(provider, accessToken);
    const userManager = createContentManager("user");
    let user = null;
    const existingUsers = await userManager.findMany({
      filters: { email: oauthUser.email },
      limit: 1,
      populate: "role"
    });
    if (existingUsers.data.length > 0) {
      user = existingUsers.data[0];
      if (user.blocked) {
        throw createError({
          statusCode: 403,
          statusMessage: "Forbidden",
          message: "Your account has been blocked"
        });
      }
    } else {
      let username = oauthUser.email.split("@")[0];
      const existingUsername = await userManager.findMany({
        filters: { username },
        limit: 1
      });
      if (existingUsername.data.length > 0) {
        username = `${username}_${Math.random().toString(36).substring(2, 8)}`;
      }
      const randomPassword = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
      const roleManager = createContentManager("role");
      const authenticatedRoles = await roleManager.findMany({
        filters: { name: "authenticated" },
        limit: 1
      });
      if (authenticatedRoles.data.length === 0) {
        throw createError({
          statusCode: 500,
          statusMessage: "Configuration Error",
          message: 'Default "authenticated" role not found. Please run database sync.'
        });
      }
      const authenticatedRole = authenticatedRoles.data[0];
      user = await userManager.create({
        username,
        email: oauthUser.email,
        password: randomPassword,
        // Random password, won't be used for OAuth login
        confirmed: true,
        // Auto-confirm OAuth users
        blocked: false,
        role: authenticatedRole.id
      });
      user.role = authenticatedRole;
    }
    const roleObj = user.role;
    const roleName = (roleObj == null ? void 0 : roleObj.name) || "authenticated";
    const jwtPayload = {
      id: user.id,
      username: user.username,
      email: user.email,
      role: roleName
    };
    const token = generateJWT(jwtPayload);
    return `
      <!DOCTYPE html>
      <html>
        <head>
          <title>Authentication Successful</title>
          <style>
            body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #f5f5f5; }
            .container { background: white; padding: 2rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); max-width: 500px; }
            h1 { color: #28a745; margin-top: 0; }
            code { background: #f4f4f4; padding: 0.2rem 0.4rem; border-radius: 3px; font-size: 0.9em; word-break: break-all; display: block; margin: 1rem 0; }
            .token { max-height: 100px; overflow-y: auto; }
          </style>
        </head>
        <body>
          <div class="container">
            <h1>\u2705 Authentication Successful!</h1>
            <p><strong>Provider:</strong> ${provider}</p>
            <p><strong>Email:</strong> ${user.email}</p>
            <p><strong>Username:</strong> ${user.username}</p>
            <p><strong>JWT Token:</strong></p>
            <code class="token">${token}</code>
            <p style="color: #666; font-size: 0.9em; margin-top: 1.5rem;">
              In a production app, you would be redirected to your frontend application with this token.
            </p>
          </div>
        </body>
      </html>
    `;
  } catch (error) {
    console.error(`[GET /api/auth/${(_b = event.context.params) == null ? void 0 : _b.provider}/callback] Error:`, error);
    if (error && typeof error === "object" && "statusCode" in error) {
      throw error;
    }
    throw createError({
      statusCode: 500,
      statusMessage: "OAuth Callback Failed",
      message: error instanceof Error ? error.message : "Unknown error"
    });
  }
});

export { callback_get as default };
//# sourceMappingURL=callback.get.mjs.map
