import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import axios from "axios";
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: any) => {
	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 loginResp = await axios.post(
			`${process.env.LST_BASE_URL}/api/user/login`,
			{ username: username.toLowerCase(), password },
			{ withCredentials: true },
		);

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

		const setCookie = loginResp.headers["set-cookie"] as any;

		if (setCookie) {
			c.header("Set-Cookie", setCookie);
		}
		return c.json(
			{ success: true, message: "Login successful", data: loginResp.data },
			200,
		);
	} catch (err) {
		// @ts-ignore
		if (!err.response.data.success) {
			// @ts-ignore
			return c.json(
				// @ts-ignore
				{ success: false, message: err.response.data.message },
				401,
			);
		} else {
			return c.json({ success: false, message: "Incorrect Credentials" }, 401);
		}
	}
});

export default app;
