// an external way to creating logs
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { responses } from "../../../globalUtils/routeDefs/responses.js";
import { authMiddleware } from "../../auth/middleware/authMiddleware.js";
import { sendEmail } from "../controller/sendMail.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { apiHit } from "../../../globalUtils/apiHits.js";

const app = new OpenAPIHono({ strict: false });

const EmailSchema = z
    .object({
        email: z.string().email().openapi({ example: "smith@example.come" }),
        subject: z.string().openapi({ example: "Welcome to LST" }),
        template: z.string().openapi({ example: "exampleTemplate" }),
        context: z
            .object({
                name: z.string().optional(),
                score: z.string().optional(),
            })
            .optional()
            .openapi({}),
    })
    .openapi("User");
app.openapi(
    createRoute({
        tags: ["server"],
        summary: "Returns current active lots that are tech released",
        method: "post",
        path: "/sendmail",
        middleware: authMiddleware,
        request: {
            body: {
                content: {
                    "application/json": { schema: EmailSchema },
                },
            },
        },
        responses: responses(),
    }),
    async (c) => {
        const { data: bodyData, error: bodyError } = await tryCatch(
            c.req.json()
        );
        apiHit(c, { endpoint: "/sendmail", lastBody: bodyData });
        if (bodyError) {
            return c.json(
                {
                    success: false,
                    message: "There was an error sending the email",
                    data: bodyError,
                },
                400
            );
        }
        const { data: emailData, error: emailError } = await tryCatch(
            sendEmail(bodyData)
        );

        if (emailError) {
            return c.json({
                success: false,
                message: "There was an error sending the email",
                data: emailError,
            });
        }

        return c.json({
            success: emailData.success,
            message: emailData.message,
            data: emailData.data,
        });
    }
);
export default app;
