import query from '../server-utils/query.js';
import { declareHandler } from '../server-utils/routesHandler.js';

/**
 * This file contains route handlers for the welcome survey.
 *
 * The welcome survey is shown to all new users, and asks them questions on where they came from and what kind of user they are.
 */

export const getWelcomeSurveyResponse = declareHandler({
  func: async (req, res) => {
    const userId = req.user.id;

    // if user was created before May 16 2024, skip the welcome survey
    const userQuery = await query(`SELECT * FROM users WHERE id = $1`, [userId]);
    const user = userQuery.rows[0];
    if (user.created_at < new Date('2024-05-16') && process.env.ENVIRONMENT !== 'development')
      return res.send({ skip: true });

    const welcomeSurveyQuery = await query(`SELECT * FROM welcome_survey_answers WHERE user_id = $1`, [userId]);
    const welcomeSurveyResponse = welcomeSurveyQuery.rows[0];
    res.send({ ...welcomeSurveyResponse });
  },
});

export const createWelcomeSurveyResponse = declareHandler({
  func: async (req, res) => {
    const { hearAboutUs, hearAboutUsDetails, describesYou } = req.body;

    await query(
      `INSERT INTO welcome_survey_answers (user_id, hear_about_us, hear_about_us_details, user_self_description) VALUES ($1, $2, $3, $4)`,
      [req.user.id, hearAboutUs, hearAboutUsDetails, describesYou]
    );

    res.send({ success: true });
  },
});
