import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { auth } from "@/auth";

import { registerSchema } from "../schemas";
import { prisma } from "@/lib/prisma";
import bcrypt from "bcryptjs";

const app = new Hono()
  .get("/current", async (c) => {
    const session = await auth();
    
    if (!session?.user) {
      return c.json({ error: "Unauthorized" }, 401);
    }

    const user = await prisma.user.findUnique({
      where: { email: session.user.email! },
      include: {
        workspaces: true
      }
    });

    return c.json({ data: user });
  })
  .post("/register", zValidator("json", registerSchema), async (c) => {
    const { name, email, password } = c.req.valid("json");

    try {
      const existingUser = await prisma.user.findUnique({
        where: { email }
      });

      if (existingUser) {
        return c.json({ error: "User already exists" }, 400);
      }

      const hashedPassword = await bcrypt.hash(password, 12);

      const user = await prisma.user.create({
        data: {
          name,
          email,
          hashedPassword,
        },
        include: {
          workspaces: true
        }
      });

      return c.json({ success: true, user });

    } catch (error) {
      console.error("Registration error:", error);
      return c.json({ error: "Registration failed" }, 500);
    }
  });

export default app;
