"use server";

import { getConnection } from "@/database/configuration/connection";
import { DBEType } from "@/models/ErrorType";
import fs from "fs";
import { ResultSetHeader } from "mysql2";
import path from "path";
import { v4 } from "uuid";

async function postLocalLog({ type, log }: ServerLog) {
  const timestamp = new Date().toISOString().replace(/:/g, "-");
  const fileName = `${timestamp}-${type}.log`;
  const filePath = path.join("log", fileName);
  const logMessage = `${timestamp} [${type}] ${log.message}\n${log.stack}`;

  try {
    await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
    await fs.promises.appendFile(filePath, logMessage);
  } catch (error) {
    console.error("Failed to write log to file:", error);
  }
}

export async function postServerLog({ type, log }: ServerLog) {
  const con = await getConnection();

  if (process.env.NODE_ENV === "development") {
    return await postLocalLog({ type, log });
  }

  if ("error" in con) {
    return false;
  }

  try {
    const [result] = await con.query<ResultSetHeader>(
      `
      INSERT INTO LOGS 
        (ID, TYPE, MESSAGE, STACK) 
      VALUES 
        (?, ?, ?, ?)
      `,
      [v4(), type, log.message, log.stack ?? "STACK NOT AVAILABLE"],
    );

    if (result.insertId) {
      return await postLocalLog({ type, log });
    }
  } catch (error) {
    await postLocalLog({ type: DBEType.ERROR, log: error });
  } finally {
    con.release();
  }
}
