import type { NextApiRequest, NextApiResponse } from 'next';
import mysql from 'mysql2/promise';

interface Review {
  id: number;
  author: string;
  rating: number;
  date: string;
  text: string;
  title?: string;
}

interface ReviewInput {
  author_name: string;
  author_email: string;
  rating: number;
  title?: string;
  text: string;
}

interface ErrorResponse {
  error: string;
}

const pool = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'perfume_shop',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Review[] | { success: boolean } | ErrorResponse>
) {
  if (req.method === 'GET') {
    try {
      const connection = await pool.getConnection();
      
      const [rows] = await connection.query<any[]>(
        `SELECT
          id,
          author_name as author,
          rating,
          DATE_FORMAT(created_at, '%d.%m.%Y') as date,
          text,
          title
        FROM reviews
        WHERE is_approved = TRUE
        ORDER BY created_at DESC
        LIMIT 100`
      );

      connection.release();

      const reviews: Review[] = rows.map(row => ({
        id: row.id,
        author: row.author,
        rating: row.rating,
        date: row.date,
        text: row.text,
        title: row.title
      }));

      return res.status(200).json(reviews);
    } catch (error) {
      return res.status(500).json({ error: 'Chyba při načítání recenzí' });
    }
  }

  if (req.method === 'POST') {
    try {
      const { author_name, author_email, rating, text, title } = req.body as ReviewInput;

      if (!author_name || !author_email || !rating || !text) {
        return res.status(400).json({ error: 'Chybí povinná pole' });
      }

      if (rating < 1 || rating > 5) {
        return res.status(400).json({ error: 'Hodnocení musí být mezi 1-5' });
      }

      if (text.length < 10) {
        return res.status(400).json({ error: 'Recenze musí mít alespoň 10 znaků' });
      }

      const connection = await pool.getConnection();

      await connection.query(
        `INSERT INTO reviews (author_name, author_email, rating, text, title, is_approved)
         VALUES (?, ?, ?, ?, ?, FALSE)`,
        [author_name, author_email, rating, text, title || null]
      );

      connection.release();

      return res.status(201).json({ success: true });
    } catch (error) {
      return res.status(500).json({ error: 'Chyba při ukládání recenze' });
    }
  }

  return res.status(405).json({ error: 'Metoda není povolena' });
}
