// pages/api/auth/[...nextauth].js
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import prisma from "@/lib/prisma";

export default NextAuth({
  secret: process.env.NEXTAUTH_SECRET,
  session: { strategy: "jwt" },

  pages: {
    signIn: "/login",
  },

  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "E-posta", type: "text" },
        password: { label: "Şifre", type: "password" },
      },

      async authorize(credentials) {
        const email = String(credentials?.email || "").trim();
        const password = String(credentials?.password || "");

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

        // NOTE: Your User model has no email field.
        // We authenticate using `name` as the login identifier (email/username).
        const user = await prisma.user.findFirst({
          where: { name: email },
        });

        if (!user) return null;

        const ok = await bcrypt.compare(password, user.pass);
        if (!ok) return null;

        return {
          id: String(user.id),
          name: user.name,
          role: user.role, // 1 admin, 2 user
        };
      },
    }),
  ],

  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.uid = user.id;
        token.role = user.role;
        token.name = user.name;
      }
      return token;
    },
    async session({ session, token }) {
      if (session?.user) {
        session.user.id = token.uid;
        session.user.role = token.role;
        session.user.name = token.name;
      }
      return session;
    },
  },
});
