import { prisma } from '@/lib/prisma';
import bcrypt from 'bcrypt';
import { User } from '@/types/auth';

/**
 * Interfaz para adapters de autenticación
 */
export interface AuthAdapter {
  /**
   * Verificar credenciales
   */
  verifyCredentials(username: string, password: string): Promise<User | null>;

  /**
   * Hashear password
   */
  hashPassword(password: string): Promise<string>;

  /**
   * Verificar password
   */
  verifyPassword(password: string, hash: string): Promise<boolean>;
}

/**
 * Adapter de autenticación usando bcrypt + Prisma
 */
class PrismaAuthAdapter implements AuthAdapter {
  /**
   * Verificar credenciales de usuario
   */
  async verifyCredentials(username: string, password: string): Promise<User | null> {
    try {
      const user = await prisma.user.findUnique({
        where: { username },
      });

      if (!user?.passwordHash) {
        return null;
      }

      const isValidPassword = await this.verifyPassword(password, user.passwordHash);

      if (!isValidPassword) {
        return null;
      }

      return {
        id: user.id,
        username: user.username,
        name: user.name || user.username,
        email: `${user.username}@local.com`,
        role: user.role,
      };
    } catch (error) {
      console.error('💥 [AUTH] Error en verifyCredentials:', error);
      return null;
    }
  }

  /**
   * Hashear password con bcrypt
   */
  async hashPassword(password: string): Promise<string> {
    return bcrypt.hash(password, 10);
  }

  /**
   * Verificar password con bcrypt
   */
  async verifyPassword(password: string, hash: string): Promise<boolean> {
    return bcrypt.compare(password, hash);
  }
}

export const authAdapter: AuthAdapter = new PrismaAuthAdapter();
