import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { supabaseEdge, corsHeaders } from '../initEdge.ts';
import { StreamChat } from "https://cdn.jsdelivr.net/npm/getstream/dist/js_min/getstream.js"

const apikey = 'xsgtgad9krw4';
const apiSecret = 'dss73ytca5cjemuvwajyuct29zta3nujxmm4qx9kzsrv2pskcbquvxp8byj9fm3t'
const chatClient = new StreamChat(apikey, apiSecret);

const createVideocall = async (clientId, expertId, speciality) => {
  const channelID = `video-call-${clientId}-${expertId}`;
  const channel = chatClient.channel('messaging', channelID, {
    name: `video-call-${speciality}`,
  })
  await channel.create()
  await channel.addMembers([clientId, expertId])
  return channel
}




serve(async req => {

  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders });
  }
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const milliseconds = String(now.getMilliseconds()).padStart(3, '0');

  const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}+00`;

  try {
    const { clientId, expertId, startTime, endTime, speciality } =
      await req.json();
    const data = {
      clientid: clientId,
      expertid: expertId,
      starttime: startTime,
      endtime: endTime,
      status: 'pending',
      createtime: formattedDate,
      speciality,
    };

    const { error } = await supabaseEdge.from('reservations').insert([data]);

    if (error) {
      throw new Error(error.message);
    }

    const channel = await createVideocall(clientId, expertId, speciality);
    const responseData = {
      ...data,
      channelId: channel.id,
      tokenClient: chatClient.createToken(clientId),
      tokenExpert: chatClient.createToken(expertId),
    }

    return new Response(JSON.stringify(responseData), {
      headers: {
        ...corsHeaders, 'Content-Type': 'application/json',

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