import type { APIRoute } from 'astro';
import { storage } from '../../lib/storage';

export const prerender = false;

export const GET: APIRoute = async ({ url }) => {
  try {
    const tag = url.searchParams.get('tag');

    let data;
    if (tag) {
      data = await storage.getWordsByTag(tag);
    } else {
      data = await storage.getAllWords();
    }

    return new Response(JSON.stringify(data), {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
      },
    });
  } catch (error) {
    console.error('Error in GET /api/vocab:', error);
    return new Response(JSON.stringify({ error: 'Failed to read vocab list' }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json',
      },
    });
  }
};

export const POST: APIRoute = async ({ request }) => {
  try {
    const data = await request.json();

    // Validate the new word
    if (!data.hindi || !data.english) {
      return new Response(JSON.stringify({ error: 'Missing required fields: hindi and english' }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json',
        },
      });
    }

    // Check if creating a new tag
    let tagIds = data.tagIds || [];
    if (data.newTag) {
      if (!data.newTag.name) {
        return new Response(JSON.stringify({ error: 'New tag requires a name' }), {
          status: 400,
          headers: {
            'Content-Type': 'application/json',
          },
        });
      }

      const newTag = await storage.createTag(data.newTag.name, data.newTag.description);
      tagIds.push(newTag.id);
    }

    const newWord = await storage.createWord({
      hindi: data.hindi,
      english: data.english,
      type: data.type,
      gender: data.gender,
      note: data.note,
      examples: data.examples,
      tagIds,
      seeAlso: data.seeAlso,
    });

    return new Response(JSON.stringify({ success: true, word: newWord }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
      },
    });
  } catch (error) {
    console.error('Error in POST /api/vocab:', error);
    return new Response(JSON.stringify({ error: 'Failed to create word' }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json',
      },
    });
  }
};
