// Follow this setup guide to integrate the Deno language server with your editor:
// https://deno.land/manual/getting_started/setup_your_environment
// This enables autocomplete, go to definition, etc.

// Import required modules
import {createClient} from 'npm:@supabase/supabase-js';
import { createClient as createStorageClient } from 'npm:@supabase/storage-js';
import { decode } from 'npm:std/encoding/base64';
import { read } from 'npm:xlsx/mod';

const supabase = createClient(
  Deno.env.get("SUPABASE_URL")!, 
  Deno.env.get("SUPABASE_ANON_KEY")!
);

const supabaseStorage = createClient(
  Deno.env.get("SUPABASE_STORAGE_URL")!, 
  Deno.env.get("SUPABASE_ANON_STORAGE_KEY")!
);

Deno.serve(async (req,res) => {

    // Get the file path from the request
    //const filePath = req.url.substring(1);
    const storage = createStorageClient(supabaseStorage);
    // Download the Excel file from Supabase Storage
    const { data: file, error: downloadError } = await storage.from('uploads/callsheet').download("FState Region ALL CHANNEL REPORTS 10 MARCH 2024.xlsx");//filePath);
    if (downloadError) {
      throw downloadError;
    }

    // Parse the Excel file
    const excelData = read(file);

    // Upload parsed data to the database
    const sheetName = excelData.SheetNames[0];
    const sheet = excelData.Sheets[sheetName];
    const parsedData = read(sheet, { header: 1 });

  const { data, error } = await supabase
      .from('report_sj')
      .upsert(parsedData);
  if(error) {
    data = {
      message: 'Uploaded unsuccessfully',
      status: 500 
    }
    throw error;
  }else{
    data = {
      message: 'Uploaded successfully',
      status: 200 
    }
  }

  return new Response(
    JSON.stringify(data),
    { headers: { "Content-Type": "application/json" } },
  )
})


/* To invoke locally:

  1. Run `supabase start` (see: https://supabase.com/docs/reference/cli/supabase-start)
  2. Make an HTTP request:

  curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/upload_sj' \
    --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0' \
    --header 'Content-Type: application/json' \
    --data '{"name":"Functions"}'

*/
