import Admin from '../db/models/Admin';
import Client from '../db/models/Client';
import redisClient from '../../config/redis';
import jwt, {JwtPayload} from 'jsonwebtoken';
import {Request, Response, NextFunction} from 'express';
import {responseJSON} from '../helpers/response-handler';

// export const saveAdmin = async (
//   req: Request,
//   res: Response,
//   next: NextFunction,
// ): Promise<void> => {
//   try {
//     const {username, email} = req.body;

//     const user = await Admin.findOne({where: {username}});
//     if (user) {
//       return responseJSON(
//         req,
//         res,
//         {
//           obj: {
//             code: 409,
//             message: 'Username already take',
//           },
//         },
//         true,
//       );
//     }

//     const emailCheck = await Admin.findOne({where: {email}});
//     if (emailCheck) {
//       return responseJSON(
//         req,
//         res,
//         {
//           obj: {
//             code: 409,
//             message: 'Email already registered',
//           },
//         },
//         true,
//       );
//     }

//     next();
//   } catch (error) {
//     console.error('Error in saveAdmin middleware:', error);
//     return responseJSON(req, res, error, true);
//   }
// };

interface AuthRequest extends Request {
  token?: string | JwtPayload;
}

export const verifyAdminSecret = (
  req: Request,
  res: Response,
  next: NextFunction,
): void => {
  const authHeader = req.header('Authorization');
  const token = authHeader?.replace('Bearer ', '');

  if (!token) {
    res.status(401).json({error: 'Access denied, token missing'});
    return;
  }

  try {
    if (token !== process.env.MASTER_CLIENT_SECRET) {
      res.status(409).json({error: 'Invalid token'});
      return;
    }

    next();
  } catch (error) {
    res.status(401).json({
      error: error.message || 'Unauthorized',
      erroror_name: error.name || 'UnknownError',
      status: 0,
      code: 10016,
    });
  }
};

export const verifyAdminToken = (
  req: Request,
  res: Response,
  next: NextFunction,
): void => {
  const authHeader = req.header('Authorization');
  const token = authHeader && authHeader.replace('Bearer ', '');

  if (!token) {
    res.status(401).json({error: 'Access denied, token missing'});
    return;
  }

  try {
    const decoded = jwt.verify(token, process.env.ADMIN_CLIENT_SECRET || '');
    (req as AuthRequest).token = decoded;

    console.log(
      `Token exists: ${token}` +
        ` Decoded userId: ${(decoded as JwtPayload).id}`,
    );
    next();
  } catch (err: any) {
    res.status(401).json({
      error: err.message,
      error_name: err.name,
      status: 0,
      code: 10016,
    });
  }
};
