File size: 2,449 Bytes
a64b653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import "https://deno.land/x/[email protected]/mod.ts";
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { createClient } from 'https://esm.sh/@supabase/[email protected]';

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const { theme, wordCount = 10 } = await req.json();
    console.log('Generating game for theme:', theme, 'with word count:', wordCount);

    // Initialize Supabase client
    const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
    const supabaseKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
    const supabase = createClient(supabaseUrl, supabaseKey);

    // Generate words using existing generate-themed-word function
    const words: string[] = [];
    const usedWords: string[] = [];

    for (let i = 0; i < wordCount; i++) {
      try {
        const response = await fetch(`${supabaseUrl}/functions/v1/generate-themed-word`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${supabaseKey}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ theme, usedWords }),
        });

        if (!response.ok) {
          throw new Error(`Failed to generate word: ${response.statusText}`);
        }

        const data = await response.json();
        if (data.word) {
          words.push(data.word);
          usedWords.push(data.word);
        }
      } catch (error) {
        console.error('Error generating word:', error);
        throw error;
      }
    }

    // Insert new game into database
    const { data: game, error: insertError } = await supabase
      .from('games')
      .insert({
        theme,
        words,
      })
      .select()
      .single();

    if (insertError) {
      throw insertError;
    }

    console.log('Successfully created game:', game);

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

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