import { serve } from "https://deno.land/std@0.168.0/http/server.ts"; import { createClient } from "https://esm.sh/@supabase/supabase-js@2"; const corsHeaders = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type", "Access-Control-Allow-Methods": "POST, OPTIONS", }; serve(async (req) => { if (req.method === "OPTIONS") { return new Response("ok", { headers: corsHeaders }); } try { const supabaseUrl = Deno.env.get("SUPABASE_URL")!; const anonKey = Deno.env.get("SUPABASE_ANON_KEY")!; const serviceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!; const resendKey = Deno.env.get("RESEND_API_KEY"); if (!resendKey) { throw new Error("Chýba RESEND_API_KEY."); } const authorization = req.headers.get("Authorization"); if (!authorization) { throw new Error("Používateľ nie je prihlásený."); } const userClient = createClient(supabaseUrl, anonKey, { global: { headers: { Authorization: authorization }, }, }); const { data: { user }, error: userError, } = await userClient.auth.getUser(); if (userError || !user || !user.email) { throw new Error("Nepodarilo sa overiť používateľa."); } const adminClient = createClient(supabaseUrl, serviceKey); const body = await req.json(); const exhibition_id = body.exhibition_id; if (!exhibition_id) { throw new Error("Chýba výstava."); } const { data: exhibition, error: exhibitionError } = await adminClient .from("exhibitions") .select("id, name") .eq("id", exhibition_id) .single(); if (exhibitionError || !exhibition) { throw new Error("Výstava sa nenašla."); } const { data: animals, error: animalsError } = await adminClient .from("animals") .select("id, category, breed, animal_number") .eq("owner_id", user.id); if (animalsError) { throw new Error("Nepodarilo sa načítať zvieratá."); } const animalIds = (animals || []).map((a) => a.id); if (animalIds.length === 0) { throw new Error("Nemáš pridané žiadne zvieratá."); } const { data: entries, error: entriesError } = await adminClient .from("entries") .select("id, animal_id") .eq("exhibition_id", exhibition_id) .in("animal_id", animalIds); if (entriesError) { throw new Error("Nepodarilo sa načítať prihlásené zvieratá."); } if (!entries || entries.length === 0) { throw new Error("Na túto výstavu nemáš prihlásené žiadne zvieratá."); } const { data: settings } = await adminClient .from("app_settings") .select("entry_fee") .eq("id", 1) .maybeSingle(); const fee = Number(settings?.entry_fee ?? 1); const total = entries.length * fee; const animalMap = new Map( (animals || []).map((a) => [a.id, a]) ); const animalList = entries.map((entry, index) => { const animal = animalMap.get(entry.animal_id); const category = animal?.category || "Zvieratá"; const breed = animal?.breed || "Neuvedené plemeno"; const number = animal?.animal_number ? ` – č. ${animal.animal_number}` : ""; return `
  • ${index + 1}. ${escapeHtml(category)} – ${escapeHtml(breed)}${escapeHtml(number)}
  • `; }).join(""); const { data: profile } = await adminClient .from("profiles") .select("first_name, last_name") .eq("id", user.id) .maybeSingle(); const fullName = [ profile?.first_name, profile?.last_name, ].filter(Boolean).join(" ") || user.email; const html = `

    ZO SZCH Koniarovce

    Potvrdenie prijatia prihlášky

    Dobrý deň, ${escapeHtml(fullName)},

    Vaša prihláška na výstavu bola úspešne prijatá.

    Výstava: ${escapeHtml(exhibition.name)}

    Prihlásené zvieratá:


    Počet zvierat: ${entries.length} ks

    Poplatok za 1 zviera: ${fee.toFixed(2)} €

    Celkový poplatok: ${total.toFixed(2)} €

    Ďakujeme za Vašu prihlášku a tešíme sa na Vašu účasť.

    S pozdravom,
    ZO SZCH Koniarovce

    `; const resendResponse = await fetch( "https://api.resend.com/emails", { method: "POST", headers: { "Authorization": `Bearer ${resendKey}`, "Content-Type": "application/json", }, body: JSON.stringify({ from: "ZO SZCH Koniarovce ", to: [user.email], subject: `Potvrdenie prihlášky – ${exhibition.name}`, html, }), } ); const resendResult = await resendResponse.json(); if (!resendResponse.ok) { throw new Error( resendResult.message || "Email sa nepodarilo odoslať." ); } return new Response( JSON.stringify({ success: true, message: "Potvrdzovací email bol odoslaný.", count: entries.length, total: total, }), { headers: { ...corsHeaders, "Content-Type": "application/json", }, status: 200, } ); } catch (error) { return new Response( JSON.stringify({ success: false, error: error instanceof Error ? error.message : "Nastala chyba.", }), { headers: { ...corsHeaders, "Content-Type": "application/json", }, status: 400, } ); } }); function escapeHtml(value: string): string { return value.replace(/[&<>"']/g, (char) => { const replacements: Record = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'", }; return replacements[char]; }); }