import { d as defineEventHandler, r as readBody, c as createError } from '../../../nitro/nitro.mjs';
import { PrismaClient } from '@prisma/client';
import jwt from 'jsonwebtoken';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'node:fs';
import 'node:path';
import 'node:crypto';
import 'node:url';

const prisma = new PrismaClient();
const login_post = defineEventHandler(async (event) => {
  const body = await readBody(event);
  const { user_id, password } = body;
  console.log("\uB85C\uADF8\uC778 \uC694\uCCAD:", { user_id, password: password ? "***" : "undefined" });
  if (!user_id || !password) {
    throw createError({
      statusCode: 400,
      statusMessage: "\uC544\uC774\uB514\uC640 \uBE44\uBC00\uBC88\uD638\uB97C \uC785\uB825\uD574\uC8FC\uC138\uC694."
    });
  }
  try {
    const user = await prisma.members.findUnique({
      where: { user_id }
    });
    console.log("\uC0AC\uC6A9\uC790 \uC870\uD68C \uACB0\uACFC:", user);
    if (!user) {
      throw createError({
        statusCode: 401,
        statusMessage: "\uC874\uC7AC\uD558\uC9C0 \uC54A\uB294 \uC544\uC774\uB514\uC785\uB2C8\uB2E4."
      });
    }
    if (user.password !== password) {
      console.log("\uBE44\uBC00\uBC88\uD638 \uBD88\uC77C\uCE58:", {
        \uC785\uB825\uB41C\uBE44\uBC00\uBC88\uD638: password,
        \uC800\uC7A5\uB41C\uBE44\uBC00\uBC88\uD638: user.password
      });
      throw createError({
        statusCode: 401,
        statusMessage: "\uBE44\uBC00\uBC88\uD638\uAC00 \uC77C\uCE58\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4."
      });
    }
    console.log("\uB85C\uADF8\uC778 \uC131\uACF5:", { user_id: user.user_id, name: user.name });
    const token = jwt.sign(
      { id: user.id, user_id: user.user_id, name: user.name, role_level: user.role_level },
      "your-secret-key",
      // 실제 서비스에서는 환경 변수로 관리
      { expiresIn: "24h" }
    );
    return {
      success: true,
      message: "\uB85C\uADF8\uC778 \uC131\uACF5",
      token,
      user: {
        id: user.id,
        user_id: user.user_id,
        name: user.name,
        role_level: user.role_level
      }
    };
  } catch (error) {
    console.error("\uB85C\uADF8\uC778 \uC624\uB958:", error);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.statusMessage || "\uB85C\uADF8\uC778 \uC911 \uC624\uB958\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4."
    });
  }
});

export { login_post as default };
