/**
 * Controller OAuth pour Google et Facebook
 */
import { OAuth2Client } from 'google-auth-library';
import { asyncHandler } from '../middleware/errorHandler.js';
import { pool } from '../../db.js';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';

const googleClient = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);

/**
 * Authentification Google OAuth
 * POST /api/auth/google
 */
export const googleLogin = asyncHandler(async (req, res) => {
  const { token } = req.body;

  if (!token) {
    return res.status(400).json({
      success: false,
      message: 'Token Google manquant',
    });
  }

  try {
    // Utiliser l'access token pour récupérer les infos utilisateur
    console.log('🔍 Validation du token Google...');
    const response = await fetch(
      `https://www.googleapis.com/oauth2/v3/userinfo?access_token=${token}`
    );

    console.log('📡 Réponse Google API:', response.status, response.statusText);

    if (!response.ok) {
      const errorText = await response.text();
      console.error('❌ Erreur Google API:', errorText);
      throw new Error('Token Google invalide');
    }

    const googleData = await response.json();
    console.log('✅ Données Google reçues:', { email: googleData.email, name: googleData.name });
    const { email, given_name, family_name, sub: googleId } = googleData;

    // Vérifier si l'utilisateur existe déjà
    let userResult = await pool.query(
      'SELECT * FROM users WHERE email = $1',
      [email]
    );

    let user;

    if (userResult.rows.length === 0) {
      // Créer un nouvel utilisateur
      const hashedPassword = await bcrypt.hash(googleId, 10); // Utiliser le Google ID comme mot de passe

      const insertResult = await pool.query(
        `INSERT INTO users (email, first_name, last_name, password, role, is_verified)
         VALUES ($1, $2, $3, $4, 'CLIENT', TRUE)
         RETURNING id, email, first_name, last_name, role, is_verified, created_at`,
        [email, given_name || 'Utilisateur', family_name || '', hashedPassword]
      );

      user = insertResult.rows[0];
    } else {
      user = userResult.rows[0];
    }

    // Générer un JWT
    const jwtToken = jwt.sign(
      {
        userId: user.id,
        email: user.email,
        role: user.role,
      },
      process.env.JWT_SECRET,
      { expiresIn: '7d' }
    );

    res.json({
      success: true,
      token: jwtToken,
      user: {
        id: user.id,
        email: user.email,
        firstName: user.first_name,
        lastName: user.last_name,
        role: user.role,
        emailVerified: user.is_verified,
      },
    });
  } catch (error) {
    console.error('Erreur Google OAuth:', error);
    res.status(401).json({
      success: false,
      message: 'Token Google invalide',
    });
  }
});

/**
 * Authentification Facebook OAuth
 * POST /api/auth/facebook
 */
export const facebookLogin = asyncHandler(async (req, res) => {
  const { token } = req.body;

  if (!token) {
    return res.status(400).json({
      success: false,
      message: 'Token Facebook manquant',
    });
  }

  try {
    // Vérifier le token Facebook
    const response = await fetch(
      `https://graph.facebook.com/me?access_token=${token}&fields=id,email,first_name,last_name`
    );

    if (!response.ok) {
      throw new Error('Token Facebook invalide');
    }

    const facebookData = await response.json();
    const { email, first_name, last_name, id: facebookId } = facebookData;

    if (!email) {
      return res.status(400).json({
        success: false,
        message: 'Email non fourni par Facebook',
      });
    }

    // Vérifier si l'utilisateur existe déjà
    let userResult = await pool.query(
      'SELECT * FROM users WHERE email = $1',
      [email]
    );

    let user;

    if (userResult.rows.length === 0) {
      // Créer un nouvel utilisateur
      const hashedPassword = await bcrypt.hash(facebookId, 10); // Utiliser le Facebook ID comme mot de passe

      const insertResult = await pool.query(
        `INSERT INTO users (email, first_name, last_name, password, role, is_verified)
         VALUES ($1, $2, $3, $4, 'CLIENT', TRUE)
         RETURNING id, email, first_name, last_name, role, is_verified, created_at`,
        [email, first_name || 'Utilisateur', last_name || '', hashedPassword]
      );

      user = insertResult.rows[0];
    } else {
      user = userResult.rows[0];
    }

    // Générer un JWT
    const jwtToken = jwt.sign(
      {
        userId: user.id,
        email: user.email,
        role: user.role,
      },
      process.env.JWT_SECRET,
      { expiresIn: '7d' }
    );

    res.json({
      success: true,
      token: jwtToken,
      user: {
        id: user.id,
        email: user.email,
        firstName: user.first_name,
        lastName: user.last_name,
        role: user.role,
        emailVerified: user.is_verified,
      },
    });
  } catch (error) {
    console.error('Erreur Facebook OAuth:', error);
    res.status(401).json({
      success: false,
      message: 'Token Facebook invalide',
    });
  }
});

export default {
  googleLogin,
  facebookLogin,
};
