import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { supabaseEdge, corsHeaders } from '../initEdge.ts'


const generateUniqueIdentifier = async (fullName: string, speciality: string) => {
  let userName
  let num = 1;

  const nameLowerCase = fullName.toLowerCase()
  const words = nameLowerCase.split(" ");
  const name = words[0];
  const initialLastName = words[1].charAt(0).toUpperCase();
  userName = `${name}${initialLastName}${speciality}`;

  while (true) {
    const { data } = await supabaseEdge
      .from('users')
      .select('username')
      .eq('username', userName);

    if (!data || data.length === 0) {
      return userName;
    }

    userName = `${name}${initialLastName}${speciality}${num}`;
    num++;
  }
};

console.log("entro en el archivo")

serve(async req=> {

if(req.method === 'OPTIONS'){
  return new Response('ok', { headers:corsHeaders});
}


  try {
    const { fullName, speciality } = await req.json();

    const uniqueIdentifier = await generateUniqueIdentifier(fullName, speciality);

    const data = {
      message: `Hello ${fullName} with expertise ${speciality}!`,
      uniqueIdentifier,
    };

    return new Response(JSON.stringify(data), {
      headers: {...corsHeaders, 'Content-Type': 'application/json',
      },
      status: 200,
    });
  } catch (error) {
    return new Response(JSON.stringify({ error:error.message }), {      
      headers: {...corsHeaders,'Content-Type': 'application/json',
      },
      status: 400,
    });
  }
});
