'use strict';

var drizzleOrm = require('drizzle-orm');
require('crypto');
var pgCore = require('drizzle-orm/pg-core');
require('bcryptjs');
require('jsonwebtoken');

// src/auth/services/drizzle-auth-service.ts
var userRole = pgCore.pgEnum("UserRole", ["USER", "ADMIN", "SUPER_ADMIN"]);
var user = pgCore.pgTable(
  "User",
  {
    id: pgCore.text().primaryKey().notNull(),
    email: pgCore.text().notNull(),
    emailVerified: pgCore.boolean().default(false).notNull(),
    username: pgCore.text().notNull(),
    password: pgCore.text(),
    name: pgCore.text(),
    nickname: pgCore.text(),
    image: pgCore.text(),
    avatar: pgCore.text(),
    role: userRole().default("USER").notNull(),
    preferences: pgCore.jsonb(),
    createdAt: pgCore.timestamp({ precision: 3, mode: "string" }).default(drizzleOrm.sql`CURRENT_TIMESTAMP`).notNull(),
    updatedAt: pgCore.timestamp({ precision: 3, mode: "string" }).notNull(),
    twoFactorEnabled: pgCore.boolean().default(false).notNull()
  },
  (table) => [
    pgCore.uniqueIndex("User_email_key").using("btree", table.email.asc().nullsLast().op("text_ops")),
    pgCore.uniqueIndex("User_username_key").using(
      "btree",
      table.username.asc().nullsLast().op("text_ops")
    )
  ]
);
var session = pgCore.pgTable(
  "Session",
  {
    id: pgCore.text().primaryKey().notNull(),
    userId: pgCore.text().notNull(),
    token: pgCore.text().notNull(),
    expiresAt: pgCore.timestamp({ precision: 3, mode: "string" }).notNull(),
    ipAddress: pgCore.text(),
    userAgent: pgCore.text(),
    createdAt: pgCore.timestamp({ precision: 3, mode: "string" }).default(drizzleOrm.sql`CURRENT_TIMESTAMP`).notNull(),
    updatedAt: pgCore.timestamp({ precision: 3, mode: "string" }).default(drizzleOrm.sql`CURRENT_TIMESTAMP`).notNull()
  },
  (table) => [
    pgCore.uniqueIndex("Session_token_key").using("btree", table.token.asc().nullsLast().op("text_ops")),
    pgCore.foreignKey({
      columns: [table.userId],
      foreignColumns: [user.id],
      name: "Session_userId_fkey"
    }).onUpdate("cascade").onDelete("cascade")
  ]
);
var account = pgCore.pgTable(
  "Account",
  {
    id: pgCore.text().primaryKey().notNull(),
    accountId: pgCore.text().notNull(),
    providerId: pgCore.text().notNull(),
    // 提供商: github, google, wechat 等
    userId: pgCore.text().notNull(),
    accessToken: pgCore.text(),
    refreshToken: pgCore.text(),
    idToken: pgCore.text(),
    accessTokenExpiresAt: pgCore.timestamp({ precision: 3, mode: "string" }),
    refreshTokenExpiresAt: pgCore.timestamp({ precision: 3, mode: "string" }),
    scope: pgCore.text(),
    password: pgCore.text(),
    createdAt: pgCore.timestamp({ precision: 3, mode: "string" }).default(drizzleOrm.sql`CURRENT_TIMESTAMP`).notNull(),
    updatedAt: pgCore.timestamp({ precision: 3, mode: "string" }).notNull()
  },
  (table) => [
    pgCore.uniqueIndex("Account_providerId_accountId_key").using(
      "btree",
      table.providerId.asc().nullsLast().op("text_ops"),
      table.accountId.asc().nullsLast().op("text_ops")
    ),
    pgCore.foreignKey({
      columns: [table.userId],
      foreignColumns: [user.id],
      name: "Account_userId_fkey"
    }).onUpdate("cascade").onDelete("cascade")
  ]
);
pgCore.pgTable(
  "verifications",
  {
    id: pgCore.text().primaryKey().notNull(),
    identifier: pgCore.text().notNull(),
    // 邮箱或手机号
    value: pgCore.text().notNull(),
    // 验证码
    expiresAt: pgCore.timestamp({ precision: 3, mode: "string" }).notNull(),
    createdAt: pgCore.timestamp({ precision: 3, mode: "string" }).default(drizzleOrm.sql`CURRENT_TIMESTAMP`).notNull()
  },
  (table) => [
    pgCore.uniqueIndex("verifications_identifier_value_key").using(
      "btree",
      table.identifier.asc().nullsLast().op("text_ops"),
      table.value.asc().nullsLast().op("text_ops")
    )
  ]
);
drizzleOrm.relations(user, ({ many }) => ({
  sessions: many(session),
  accounts: many(account)
}));
drizzleOrm.relations(session, ({ one }) => ({
  user: one(user, {
    fields: [session.userId],
    references: [user.id]
  })
}));
drizzleOrm.relations(account, ({ one }) => ({
  user: one(user, {
    fields: [account.userId],
    references: [user.id]
  })
}));
function getTokenFromRequest(request) {
  const cookieHeader = request.headers.get("Cookie");
  if (cookieHeader) {
    const match = cookieHeader.match(/auth_token=([^;]+)/);
    if (match && match[1]) {
      return match[1];
    }
  }
  const authHeader = request.headers.get("Authorization");
  if (authHeader && authHeader.startsWith("Bearer ")) {
    const token = authHeader.substring(7);
    return token || null;
  }
  return null;
}

// src/auth/middleware/with-auth.ts
function createAuthMiddleware(config) {
  function withAuth(handler, level = "user") {
    return async (request, context = {}) => {
      if (level === "none") {
        return await handler(request, context);
      }
      try {
        const token = getTokenFromRequest(request);
        if (!token) {
          return new Response(
            JSON.stringify({
              success: false,
              error: "\u672A\u63D0\u4F9B\u8BA4\u8BC1\u4EE4\u724C"
            }),
            {
              status: 401,
              headers: { "Content-Type": "application/json" }
            }
          );
        }
        const result = await config.authService.verifyToken(token);
        if (level === "admin" || level === "super_admin") {
          if (!["ADMIN", "SUPER_ADMIN"].includes(result.user.role)) {
            return new Response(
              JSON.stringify({
                success: false,
                error: "\u9700\u8981\u7BA1\u7406\u5458\u6743\u9650"
              }),
              {
                status: 403,
                headers: { "Content-Type": "application/json" }
              }
            );
          }
        }
        if (level === "super_admin") {
          if (result.user.role !== "SUPER_ADMIN") {
            return new Response(
              JSON.stringify({
                success: false,
                error: "\u9700\u8981\u8D85\u7EA7\u7BA1\u7406\u5458\u6743\u9650"
              }),
              {
                status: 403,
                headers: { "Content-Type": "application/json" }
              }
            );
          }
        }
        context.user = result.user;
        context.session = result.session;
        return await handler(request, context);
      } catch (error) {
        console.error("Auth middleware error:", error);
        return new Response(
          JSON.stringify({
            success: false,
            error: "\u8BA4\u8BC1\u5931\u8D25"
          }),
          {
            status: 401,
            headers: { "Content-Type": "application/json" }
          }
        );
      }
    };
  }
  function requireAuth(handler) {
    return withAuth(handler, "user");
  }
  function requireAdmin(handler) {
    return withAuth(handler, "admin");
  }
  function requireSuperAdmin(handler) {
    return withAuth(handler, "super_admin");
  }
  return {
    withAuth,
    requireAuth,
    requireAdmin,
    requireSuperAdmin
  };
}

exports.createAuthMiddleware = createAuthMiddleware;
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map