import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import { authConfig } from "./auth.config";

const ADMIN_PASSWORD_HASH = process.env.ADMIN_PASSWORD_HASH || "";
const GUEST_PASSWORD_HASH = process.env.GUEST_PASSWORD_HASH || "";

type UserWithRole = { id: string; name: string; role: "admin" | "viewer" };

export const { handlers, auth, signIn, signOut } = NextAuth({
  ...authConfig,
  providers: [
    Credentials({
      credentials: {
        username: { label: "Korisničko ime", type: "text" },
        password: { label: "Lozinka", type: "password" },
      },
      async authorize(credentials): Promise<UserWithRole | null> {
        const username = credentials?.username as string;
        const password = credentials?.password as string;

        if (!username || !password) return null;

        if (username === process.env.AUTH_USER_USERNAME) {
          const valid = await bcrypt.compare(password, ADMIN_PASSWORD_HASH);
          if (!valid) return null;
          return { id: "1", name: username, role: "admin" };
        }

        if (username === "gost") {
          const valid = await bcrypt.compare(password, GUEST_PASSWORD_HASH);
          if (!valid) return null;
          return { id: "2", name: "gost", role: "viewer" };
        }

        return null;
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }) {
      if (user) token.role = (user as UserWithRole).role;
      return token;
    },
    async session({ session, token }) {
      if (session.user) (session.user as UserWithRole & typeof session.user).role = token.role as "admin" | "viewer";
      return session;
    },
  },
  session: { strategy: "jwt" },
});
