import { Client } from '@notionhq/client';
import { declareHandler } from '../server-utils/routesHandler.js';

/**
 * This file contains the endpoint for saving feedback.
 *
 * Users can send feedback from our app and it sends it to Notion
 * for us to review.
 * https://www.notion.so/34a3bc215f7641b98a7a2f95a9805dde
 */

const notion = new Client({ auth: process.env.NOTION_SECRET });
const databaseId = process.env.NOTION_FEEDBACK_DB_ID;

async function addFeedbackItem(username: string, email: string, plan: string, text: string) {
  const time = new Date().toISOString();
  try {
    await notion.pages.create({
      parent: { database_id: databaseId },
      properties: {
        username: { title: [{ text: { content: username } }] },
        email: { email },
        // Note: taking the position that Trials shouldn't be counted here. You get priority if you're actually paying us.
        pro: { select: { name: plan === 'Pro' ? 'Y' : 'N' } },
        indie: { select: { name: plan === 'Indie' ? 'Y' : 'N' } },
        feedback: { rich_text: [{ text: { content: text } }] },
        submitted: { date: { start: time } },
      },
    });
  } catch (error) {
    console.error(error.body);
  }
}

export const saveFeedback = declareHandler({
  func: async (req, res) => {
    const { feedback = '' } = req.body;
    await addFeedbackItem(
      req.user?.username || 'Unknown',
      req.user?.email || 'Unknown',
      req.user?.plan || 'Unknown',
      feedback
    );
    res.status(200);
    res.send({ status: 'success' });
  },
});
