import type { NextApiRequest, NextApiResponse } from 'next';
import mysql from 'mysql2/promise';
import jwt from 'jsonwebtoken';
import { sendEmail } from '@/lib/mail';

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

type ResponseData = {
  success?: boolean;
  message?: string;
  error?: string;
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { email } = req.body;

  // Validation
  if (!email) {
    return res.status(400).json({ error: 'Email je povinný' });
  }

  try {
    const connection = await pool.getConnection();

    try {
      // Find user by email
      const [users]: any = await connection.query(
        'SELECT id, first_name, last_name, email FROM users WHERE email = ?',
        [email]
      );

      // Neříkejme jestli email existuje či ne (bezpečnost)
      if (users.length === 0) {
        return res.status(200).json({
          success: true,
          message: 'Pokud účet s tímto emailem existuje, obdržíte instrukce na reset hesla.',
        });
      }

      const user = users[0];

      // Generuj reset token (JWT s 24h expirací)
      const jwtSecret = process.env.JWT_SECRET;
      if (!jwtSecret) {
        throw new Error('JWT_SECRET is not configured');
      }

      const resetToken = jwt.sign(
        {
          id: user.id,
          email: user.email,
          type: 'password_reset',
        },
        jwtSecret,
        { expiresIn: '24h' }
      );

      // Ulož reset token do DB
      // Nejdřív zkontroluj jestli tabulka má sloupce pro reset token
      try {
        // Pokus se aktualizovat sloupec - pokud neexistuje, bude error
        await connection.query(
          'UPDATE users SET reset_token = ?, reset_token_expires = DATE_ADD(NOW(), INTERVAL 24 HOUR) WHERE id = ?',
          [resetToken, user.id]
        );
      } catch (dbError: any) {
        // Pokud sloupec neexistuje, pokus se ho vytvořit
        if (dbError.code === 'ER_BAD_FIELD_ERROR') {
          await connection.query(
            'ALTER TABLE users ADD COLUMN reset_token VARCHAR(500), ADD COLUMN reset_token_expires DATETIME'
          );
          await connection.query(
            'UPDATE users SET reset_token = ?, reset_token_expires = DATE_ADD(NOW(), INTERVAL 24 HOUR) WHERE id = ?',
            [resetToken, user.id]
          );
        } else {
          throw dbError;
        }
      }

      const resetUrl = `${process.env.NEXT_PUBLIC_APP_URL}/reset-password?token=${encodeURIComponent(resetToken)}`;

      const emailContent = {
        to: user.email,
        subject: '🔐 Reset hesla - VYSTŘÍKEJ TO',
        html: `<!DOCTYPE html>
<html lang="cs">
<head>
  <meta charset="UTF-8">
  <title>Reset hesla - VYSTŘÍKEJ TO</title>
</head>
<body style="margin:0; padding:0; background:#f0f0f0; font-family:Arial, sans-serif;">
  <table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" bgcolor="#f0f0f0">
    <tr>
      <td align="center" style="padding:30px 15px;">
        <table role="presentation" cellpadding="0" cellspacing="0" border="0" width="600"
               style="background:#1c1c1c; border-radius:20px; overflow:hidden;">
          <tr>
            <td style="padding:40px 30px 30px 30px; text-align:center; color:#ffffff;">

              <div style="font-size:28px; font-weight:bold; color:#f4c542; margin:0; line-height:1.2;">VYSTŘÍKEJ TO</div>
              <div style="font-size:14px; color:#cccccc; margin:0 0 20px;">CELÉ PARFÉMY</div>

              <div style="height:1px; background:#f4c542; width:100%; margin:20px 0;"></div>

              <div style="font-size:22px; font-weight:bold; margin:0 0 20px;">Reset hesla</div>

              <div style="font-size:15px; line-height:1.6; text-align:left; max-width:500px; margin:0 auto; color:#dddddd;">
                <p>Dobrý den, <strong>${user.first_name} ${user.last_name}</strong>,</p>

                <p>obdrželi jsme žádost o resetování hesla pro Váš účet na <strong>VYSTŘÍKEJ TO</strong>.
                Pokud jste tuto žádost nepodali, ignorujte tento email.</p>


              <table role="presentation" cellpadding="0" cellspacing="0" border="0" align="center" style="margin:20px auto;">
                <tr>
                  <td bgcolor="#f4c542" style="border-radius:6px;">
                    <a href="${resetUrl}"
                       style="display:inline-block; padding:14px 28px; font-size:16px; font-weight:bold;
                              color:#000000; text-decoration:none;">
                      Resetovat heslo
                    </a>
                  </td>
                </tr>
              </table>
                <div style="background:#3a2f00; border:1px solid #f4c542; padding:12px 15px; border-radius:6px; margin:20px 0; color:#f4c542; font-size:14px;">
                  Tento odkaz je platný pouze 24 hodin z bezpečnostních důvodů.
                </div>

              </div>

              <div style="font-size:14px; line-height:1.5; text-align:left; max-width:500px; margin:20px auto; color:#dddddd;">
                <p><strong>Pokud nefunguje tlačítko</strong>, zkopírujte a vložte následující odkaz do vašeho prohlížeče:</p>
                <div style="background:#2a2a2a; padding:12px; border-radius:5px; font-family:monospace; font-size:13px; word-break:break-all; color:#f4c542;">
                  ${resetUrl}
                </div>
              </div>

            </td>
          </tr>
        </table>

        <table role="presentation" cellpadding="0" cellspacing="0" border="0" width="600"
               style="margin-top:20px; font-size:12px; color:#999999;">
          <tr>
            <td align="center" style="padding:10px;">
              Pokud máte jakékoliv otázky, neváhejte nás kontaktovat na
              <a href="mailto:${process.env.CONTACT_EMAIL}" style="color:#f4c542; text-decoration:none;">${process.env.CONTACT_EMAIL}</a><br>
              © 2026 VYSTŘÍKEJ TO – Všechna práva vyhrazena
            </td>
          </tr>
        </table>

      </td>
    </tr>
  </table>
</body>
</html>`,
        text: `
Reset hesla

Ahoj ${user.first_name} ${user.last_name},

obdrželi jsme žádost o reset hesla pro váš účet na VYSTŘÍKEJ TO. Pokud jste tuto žádost nepodali, ignorujte tento email.

Tento odkaz je platný pouze 24 hodin z bezpečnostních důvodů.

${resetUrl}

Pokud máte jakékoliv otázky, neváhejte nás kontaktovat na ${process.env.CONTACT_EMAIL}

© 2026 VYSTŘÍKEJ TO – Všechna práva vyhrazena
        `,
      };

      try {
        await sendEmail(emailContent);
      } catch (emailError) {
      }

      return res.status(200).json({
        success: true,
        message: 'Pokud účet s tímto emailem existuje, obdržíte instrukce na reset hesla.',
      });
    } finally {
      connection.release();
    }
  } catch (error) {
    return res.status(500).json({
      error: 'Chyba při zpracování žádosti. Prosím zkuste znovu.',
    });
  }
}
