import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
import { login } from "../controllers/login.js";

const app = new OpenAPIHono();

const UserSchema = z
  .object({
    username: z.string().optional().openapi({ example: "smith002" }),
    //email: z.string().optional().openapi({example: "s.smith@example.com"}),
    password: z.string().openapi({ example: "password123" }),
  })
  .openapi("User");

const route = createRoute({
  tags: ["Auth"],
  summary: "Login as user",
  description: "Login as a user to get a JWT token",
  method: "post",
  path: "/login",
  request: {
    body: {
      content: {
        "application/json": { schema: UserSchema },
      },
    },
  },
  responses: {
    200: {
      content: {
        "application/json": {
          schema: z.object({
            success: z.boolean().openapi({ example: true }),
            message: z.string().openapi({ example: "Logged in" }),
          }),
        },
      },
      description: "Response message",
    },

    400: {
      content: {
        "application/json": {
          schema: z.object({
            success: z.boolean().openapi({ example: false }),
            message: z
              .string()
              .openapi({ example: "Username and password required" }),
          }),
        },
      },
      description: "Bad request",
    },
    401: {
      content: {
        "application/json": {
          schema: z.object({
            success: z.boolean().openapi({ example: false }),
            message: z
              .string()
              .openapi({ example: "Username and password required" }),
          }),
        },
      },
      description: "Bad request",
    },
  },
});

app.openapi(route, async (c) => {
  const { username, password, email } = await c.req.json();

  if (!username || !password) {
    return c.json(
      {
        success: false,
        message: "Username and password are required",
      },
      400
    );
  }

  try {
    const { token, user } = await login(username.toLowerCase(), password);

    // Set the JWT as an HTTP-only cookie
    //c.header("Set-Cookie", `auth_token=${token}; HttpOnly; Secure; Path=/; SameSite=None; Max-Age=3600`);

    return c.json(
      { success: true, message: "Login successful", user, token },
      200
    );
  } catch (err) {
    return c.json({ success: false, message: "Incorrect Credentials" }, 401);
  }
});

export default app;
