import { onRequest } from 'firebase-functions/v2/https';
import { logger } from 'firebase-functions/v2';
import { defineSecret } from 'firebase-functions/params';
import { initializeApp, getApps } from 'firebase-admin/app';
import sgMail from '@sendgrid/mail';

import type { BoardAccessMode } from '../types/boardItem';

import { corsMiddlewareHandler, SendEmail } from '../config';

/* ─── Boiler-plate init ───────────────────────────────────────── */
if (!getApps().length) initializeApp();
const SENDGRID_API_KEY = defineSecret('SENDGRID_API_KEY');
let isSendGridInitialized = false;

/* ─── Cloud Function entry ────────────────────────────────────── */
export const boardMail = onRequest(
  {
    region: 'asia-northeast3',
    secrets: [SENDGRID_API_KEY], // ❷ declare dependency
  },
  async (req, res) => {
    return corsMiddlewareHandler(req, res, async () => {
      /* one-time SendGrid init per cold start */
      if (!isSendGridInitialized) {
        const apiKey = process.env.SENDGRID_API_KEY;
        if (!apiKey) {
          logger.error('SendGrid API key is undefined. Check secret setup.');
          throw new Error('Missing SendGrid API key');
        }
        sgMail.setApiKey(apiKey);
        isSendGridInitialized = true;
      }
      /* 1. Method guard --------------------------------------------------- */
      if (req.method !== 'POST') {
        res.status(405).send({ message: 'Method Not Allowed' });
        return;
      }
      /* 2. Extract params ------------------------------------------------- */
      const { access = 'public', subject, html, action = '' } = req.body ?? {};

      if (!['public', 'private', 'admin'].includes(access)) {
        logger.warn(`Invalid access mode: ${access}`);
        res.status(400).send({ message: 'Bad access mode' });
        return;
      }

      const effectiveAccess = access as BoardAccessMode; // ❹ always public/param
      logger.info('boardMail: effectiveAccess', effectiveAccess);
      if (!subject || !html) {
        res.status(400).send({ message: 'Missing subject or html' });
        return;
      }

      try {
        await sgMail.send({
          to: SendEmail.to,
          from: SendEmail.from,
          subject,
          html,
        });

        logger.info(
          `[boardMail] Email sent successfully via SendGrid [${action}]`,
        );
        res.status(200).send({ message: 'Email sent' });
      } catch (err) {
        logger.error('[boardMail] Error sending email', err as Error);
        res.status(500).send({ message: 'Internal Server Error' });
      }
    });
  },
);
