const express = require("express");
const app = express();
const Sequelize = require("sequelize");
const db = require("../../models/migration");
const ApiKey = db.apiKey;

async function apiKey(req, res, next) {
  const api_key = req.get("ApiKey");

  if (!api_key) {

    return res.status(401).json({
      success: false,
      message: "API Key is missing",
      code: 401,
    });
  }

  try {

    const apiKeyData = await ApiKey.findOne({
      where: {
        api_key: api_key,
        is_actived: 1,
      },
    });

    if (!apiKeyData) {

      return res.status(401).json({
        success: false,
        message: "Unauthorized",
        code: 401,
      });
    }

    next();
  } catch (err) {
    console.error("Error querying API key from database:", err);
    return res.status(500).json({
      success: false,
      message: "Internal Server Error",
      code: 500,
    });
  }
}

module.exports = apiKey;
