import { app, adminApp } from "@/firebase";
import { AgentUser } from "@/interfaces/user";
import { sessionOptions } from "@/lib/session";
import client from "@/lib/mongodb";
import { withIronSessionApiRoute } from "iron-session/next";
import { NextApiRequest, NextApiResponse } from "next";
import countryCodes from "country-codes-list";

const db = client.db(process.env.MONGODB_DB);

export default withIronSessionApiRoute(user, sessionOptions);

interface Contact {
  name: string;
  email: string;
  number: string;
}
async function get(req: NextApiRequest, res: NextApiResponse) {
  const { code, language = "en" } = req.query as {
    code: string;
    language: string;
  };

  const docs = await db.collection("users").find<AgentUser>({
    type: "agent",
    "demographicInformation.country": code
  }).toArray();
  
  const entries = docs.map((user: AgentUser) => {
    const newUser = {
      name:
        (language === "en"
          ? user.agentInformation?.companyName
          : user.agentInformation?.companyArabName ||
            user.agentInformation?.companyName) || user.name,
      email: user.email,
      number: user.demographicInformation?.phone as string,
    } as Contact;
    return newUser;
  }) as Contact[];

  const country = countryCodes.findOne(
    "countryCode" as any,
    code.toUpperCase(),
  );
  const key = language === "ar" ? "countryNameLocal" : "countryNameEn";

  res.json({
    label: country[key],
    entries,
  });
}

async function user(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === "GET") return get(req, res);
}
