import type { Request, Response, NextFunction } from "express";
import bcrypt from "bcryptjs";
import { config } from "../config.js";

function unauthorized(res: Response): void {
  res.status(401).json({ error: "Yetkisiz" });
}

export async function basicAuth(req: Request, res: Response, next: NextFunction): Promise<void> {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith("Basic ")) {
    unauthorized(res);
    return;
  }

  const encoded = authHeader.slice("Basic ".length).trim();
  const decoded = Buffer.from(encoded, "base64").toString("utf-8");
  const [username, password] = decoded.split(":");

  if (!username || !password || username !== config.AUTH_USERNAME) {
    unauthorized(res);
    return;
  }

  const isValid = await bcrypt.compare(password, config.AUTH_PASSWORD_HASH);
  if (!isValid) {
    unauthorized(res);
    return;
  }

  next();
}
