import type { APIRoute } from 'astro';
import {
  getIdeas,
  getIdea,
  getIdeaComments,
  createIdea,
  voteIdea,
  addComment,
  getStats,
  getTopIdeas,
  getIdeasByVoteThreshold,
  submitProductIdea,
} from '../../../lib/platform-queries.js';
import { createHash } from 'crypto';

export const prerender = false;

const json = (data: any, status = 200) =>
  new Response(JSON.stringify(data), {
    status,
    headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' },
  });

function fingerprint(request: Request): string {
  const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown';
  const ua = request.headers.get('user-agent') || '';
  return createHash('sha256').update(`${ip}:${ua}`).digest('hex').slice(0, 16);
}

export const GET: APIRoute = async ({ params, url }) => {
  const route = params.route || '';
  const parts = route.split('/');

  try {
    if (route === 'ideas') {
      const ideas = await getIdeas('votes');
      return json(ideas);
    }

    if (route === 'ideas/new') {
      const ideas = await getIdeas('new');
      return json(ideas);
    }

    if (route === 'ideas/top') {
      const limit = parseInt(url.searchParams.get('limit') || '10');
      const ideas = await getTopIdeas(limit);
      return json(ideas);
    }

    if (route === 'ideas/threshold') {
      const threshold = parseInt(url.searchParams.get('min') || '25');
      const ideas = await getIdeasByVoteThreshold(threshold);
      return json(ideas);
    }

    if (parts[0] === 'idea' && parts[1]) {
      const idea = await getIdea(parseInt(parts[1]));
      if (!idea) return json({ error: 'Not found' }, 404);
      const comments = await getIdeaComments(idea.id);
      return json({ idea, comments });
    }

    if (route === 'stats') {
      return json(await getStats());
    }

    return json({ error: 'Not found' }, 404);
  } catch (err: any) {
    console.error('[platform]', err);
    return json({ error: 'Server error' }, 500);
  }
};

export const POST: APIRoute = async ({ params, request }) => {
  const route = params.route || '';

  try {
    if (route === 'ideas') {
      const body = await request.json();
      if (!body.title?.trim() || !body.problem?.trim()) {
        return json({ error: 'Titlul si problema sunt obligatorii.' }, 400);
      }
      if (body.title.length > 200 || body.problem.length > 2000) {
        return json({ error: 'Text prea lung.' }, 400);
      }
      const id = await createIdea({
        title: body.title.trim(),
        problem: body.problem.trim(),
        solution: body.solution?.trim(),
        category: body.category,
        author_name: body.author_name?.trim(),
        author_email: body.author_email?.trim(),
        author_city: body.author_city?.trim(),
      });
      return json({ id, message: 'Ideea ta a fost adaugata!' }, 201);
    }

    if (route === 'vote') {
      const body = await request.json();
      if (!body.idea_id) return json({ error: 'Missing idea_id' }, 400);
      const fp = fingerprint(request);
      const result = await voteIdea(body.idea_id, fp);
      return json(result);
    }

    if (route === 'comment') {
      const body = await request.json();
      if (!body.idea_id || !body.content?.trim()) {
        return json({ error: 'Continutul e obligatoriu.' }, 400);
      }
      if (body.content.length > 1000) {
        return json({ error: 'Comentariu prea lung.' }, 400);
      }
      await addComment(body.idea_id, body.author_name, body.content.trim());
      return json({ message: 'Comentariu adaugat.' }, 201);
    }

    if (route === 'submit-product') {
      const body = await request.json();
      if (!body.title?.trim() || !body.description?.trim() || !body.category?.trim() || !body.demo_url?.trim()) {
        return json({ error: 'Titlul, descrierea, categoria si URL-ul demo sunt obligatorii.' }, 400);
      }
      if (!body.author_name?.trim() || !body.author_email?.trim()) {
        return json({ error: 'Numele si email-ul autorului sunt obligatorii.' }, 400);
      }
      if (body.title.length > 200) {
        return json({ error: 'Titlul e prea lung (max 200 caractere).' }, 400);
      }
      if (body.description.length > 2000) {
        return json({ error: 'Descrierea e prea lunga (max 2000 caractere).' }, 400);
      }

      const id = await submitProductIdea({
        title: body.title.trim(),
        description: body.description.trim(),
        category: body.category.trim(),
        demo_url: body.demo_url.trim(),
        source_url: body.source_url?.trim() || null,
        screenshot_url: body.screenshot_url?.trim() || null,
        solves_ideas: body.solves_ideas?.trim() || null,
        author_name: body.author_name.trim(),
        author_email: body.author_email.trim(),
        author_location: body.author_location?.trim() || null,
        author_github: body.author_github?.trim() || null,
      });
      return json({ id, message: 'Produsul a fost trimis pentru revizuire.' }, 201);
    }

    return json({ error: 'Not found' }, 404);
  } catch (err: any) {
    console.error('[platform POST]', err);
    return json({ error: 'Server error' }, 500);
  }
};
