import apiAuth from "@/lib/apiAuth";
import { auditLogRaw } from "@/lib/audit";
import { AliasEntry, createAliasEntry } from "@/lib/db";
import { generateAliasEmail } from "@/lib/util-server";
import { NextResponse } from "next/server";

/**
 * @swagger
 * /api/aliases/temporary:
 *   post:
 *     description: Creates a new temporary alias
 *     requestBody:
 *       description: The options for the alias
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               label:
 *                 type: string
 *                 example: "reddit"
 *               style:
 *                 type: string
 *                 enum: [words, random]
 *               labelAtEnd:
 *                 type: boolean
 *     security:
 *       - api_key: []
 *     responses:
 *       200:
 *         description: The created alias
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 id:
 *                   type: number
 *                 address:
 *                   type: string
 *                   example: "your@primary.email"
 *                 alias:
 *                   type: string
 *                   example: "reddit-whypark@t.amogus.cloud"
 *                 pending:
 *                   type: boolean
 *                 temporary:
 *                   type: boolean
 */
export async function POST(request: Request) {
  return await apiAuth(request, async (request, user) => {
    const body = await request.json();
    if (typeof body.label != "string") return new Response('"label" not provided', { status: 400 });
    if (!body.label.length || body.label.length > 16) return new Response('"label" must be between 1 and 16 characters long', { status: 400 });
    if (typeof body.style != "string") return new Response('"style" not provided', { status: 400 });
    if (typeof body.labelAtEnd != 'boolean') return new Response('"labelAtEnd" not provided', { status: 400 });

    const email = await generateAliasEmail(body.label, body.style, body.labelAtEnd);
    const id = await createAliasEntry(
      user,
      email,
      false,
      true,
    );

    const alias: AliasEntry = {
      id: id,
      address: user,
      alias: email,
      pending: false,
      temporary: true,
    };

    await auditLogRaw({
      action: "createTempAlias",
      ts: new Date().toISOString(),
      data: alias,
      user: user,
    });
    return NextResponse.json(alias);
  });
}