import * as Sentry from "@sentry/node"
import { prisma } from "@codeflash-ai/common"
import { loadAndRenderHtml, sendEmail } from "../resend/email-service.js"
import { Response, Request } from "express"
import { logger } from "../utils/logger.js"
import { internalServerError } from "../exceptions/index.js"

export async function sendOptimizationCompletedEmail(req: Request, res: Response): Promise<void> {
  const user = await prisma.users.findUnique({
    where: { user_id: (req as any).userId },
  })

  if (user?.email && user?.name) {
    const { repo, owner } = req.body
    const showRepo = owner && repo
    try {
      const html = await loadAndRenderHtml("./resend/completed_optimization_email_template.html", {
        userName: user.github_username,
        ...{
          PR: showRepo
            ? `  <div style="text-align: center; margin: 30px 0;">
          <a href="https://github.com/${owner}/${repo}/pulls/app%2Fcodeflash-ai" class="cta-button">
            <span class="pr-icon">🔀</span>
            View Pull Requests
          </a>
        </div>
      </div>`
            : "",
          repoHtml: showRepo
            ? `<a
          href="https://github.com/${owner}/${repo}"
          target="_blank"
          style="text-decoration: none; color: inherit"
        >
          <div class="repo-info">
            <img
              class="repo-avatar"
              src="https://github.com/${owner}.png?size=20"
              alt="${owner}'s avatar"
            />
            <div class="repo-name-text">${owner}/${repo}</div>
          </div>
        </a>`
            : "",
        },
      })
      await sendEmail({
        to: String(user.email),
        subject: `Codeflash: Optimization Completed${showRepo ? ` For ${owner}/${repo}` : ""}`,
        html,
      })

      logger.info("Optimization completed email sent successfully", req, {
        userEmail: user.email,
        repo: showRepo ? `${owner}/${repo}` : undefined,
      })

      res.status(200).json({ status: "success", message: "Email has been successfully sent." })
    } catch (error) {
      logger.errorWithSentry(
        "Failed to send optimization completed email",
        req,
        {
          userEmail: user.email,
          repo: showRepo ? `${owner}/${repo}` : undefined,
        },
        error as Error,
      )
      Sentry.captureException(error)
      throw internalServerError("Failed to send optimization completed email")
    }
  }
}
