"use server";

import ListSubDomains from "@/lib/cpanel/api2/SubDomain/ListSubDomains";
import { getCpanelVars } from "@/models/cpanel";
import Groq from "groq-sdk";

const systemPrompt =
  "You are a consultant and you are going to generate an array of 10 possible subdomain names. Each name must be longer than 5 characters and no longer than 25 characters. The names must make sense with the company name. Do not enter words that do not exist in the company. The response must be just the array of names";
const userPrompt =
  "Suggest me 10 possible alphanumeric subdomain names taking into account the company name I will give you at the end. just the subdomain, no protocol, second or first level domain, try to make the names concise but not too short, the preferred width should be 10 characters. the response should be in the form of an array js: ";

type GetSubdomain = {
  name: string;
  apiKey: string;
};

export async function getSubdomain({ name, apiKey }: GetSubdomain) {
  const groq = new Groq({ apiKey });

  let subdomain = "";

  const userContent = userPrompt + name;

  do {
    const response = await groq.chat.completions.create({
      model: "llama3-70b-8192",
      messages: [
        {
          role: "system",
          content: systemPrompt,
        },
        {
          role: "user",
          content: userContent,
        },
      ],
    });

    const regex = /\[[^\[\]]*\]/;
    const result = response.choices[0].message.content.match(regex);

    if (!result) {
      continue;
    }

    const subdomainList = JSON.parse(result[0]);

    for (const name of subdomainList) {
      const data = await ListSubDomains({
        regex: `${name.trim()}`,
      });

      if (data.cpanelresult.data.length > 0) {
        continue;
      } else {
        subdomain = name;
        break;
      }
    }
  } while (!subdomain);

  return subdomain.toLocaleLowerCase();
}
