import { $Enums } from "@prisma/client";
import { FastifyReply, FastifyRequest } from "fastify";
import { mail } from "../../utils/mail";
import prisma from "../../utils/prisma";
import { IdParamsSchema } from "../../utils/schema";

import axios from "axios";

import {
  EmailSchema,
  NotificationSchema,
  SmsSchema,
  UserActiveSchema,
  UserMemberSchema,
} from "./schema";
import { sendSmsAuto } from "../../services/smsGateway";

// -------------------------------------------------------------------------

export async function getUsers(req: FastifyRequest, reply: FastifyReply) {
  const users = await prisma.user.findMany({
    where: {
      role: $Enums.Role.User,
    },
    select: {
      id: true,
      civility: true,
      firstName: true,
      lastName: true,
      email: true,
      phoneNumber: true,
      active: true,
      member: true,
      position: true,
      createdAt: true,
    },
    orderBy: {
      createdAt: "desc",
    },
  });

  return reply.code(200).send(users);
}

// -------------------------------------------------------------------------
export async function sendEmail(
  req: FastifyRequest<{ Body: EmailSchema }>,
  reply: FastifyReply
) {
  const data = req.body;
  
  console.log('📧 ============ DÉBUT ENVOI EMAIL ============');
  console.log('📋 Données reçues:', JSON.stringify(data, null, 2));
  console.log('👤 IDs utilisateurs cibles:', data.users);
  
  const users = await prisma.user.findMany({
    where: {
      id: { in: data.users },
      role: $Enums.Role.User,
    },
    select: { 
      id: true,
      email: true,
      firstName: true,
      lastName: true 
    },
  });

  console.log('👥 UTILISATEURS TROUVÉS:', JSON.stringify(users, null, 2));
  console.log('🔢 Nombre d\'utilisateurs:', users.length);

  // Vérification de la configuration Mailgun
  console.log('🔧 CONFIG MAILGUN:');
  console.log('   - Domain: ccis-agadir.com');
  console.log('   - API Key présent:', !!process.env.MAILGUN_API_KEY);
  console.log('   - Expéditeur configuré: "CCIS Souss Massa <noreply@ccis-agadir.com>"');

  // Vérification de la configuration Nodemailer (ancien système)
  console.log('🔧 CONFIG NODEMAILER:');
  console.log('   - Host:', process.env.EMAIL_HOST);
  console.log('   - User:', process.env.EMAIL_HOST_USER);
  console.log('   - Expéditeur actuel:', process.env.EMAIL_HOST_USER);

  let results = {
    total: users.length,
    success: 0,
    failed: 0,
    details: [] as any[]
  };

  await Promise.all(
    users.map(async (user) => {
      console.log(`\n🔄 TENTATIVE ENVOI À: ${user.email}`);
      console.log(`   👤 ${user.firstName} ${user.lastName} (ID: ${user.id})`);
      
      try {
        // TEST avec Mailgun
        console.log('   📤 Utilisation de MAILGUN...');
        const mailgunData = {
          from: "CCIS Souss Massa <ccisa@ccis-agadir.com>",
          to: user.email,
          subject: data.subject,
          html: data.body,
          'h:Reply-To': 'ccisa@ccis-agadir.com'
        };
        
        console.log('   📨 DONNÉES MAILGUN:', JSON.stringify(mailgunData, null, 2));
        
////////        const result = await mg.messages.create('ccis-agadir.com', mailgunData);
        
        console.log(`   ✅ MAILGUN SUCCÈS pour ${user.email}`);
        console.log('   📦 Réponse Mailgun:', JSON.stringify(results, null, 2));
        
        results.success++;
        results.details.push({
          userId: user.id,
          email: user.email,
          status: 'success',
          service: 'mailgun',
          messageId: results.details[0]?.id || "unknown"
        });

      } catch (mailgunError: any) {
        console.error(`   ❌ MAILGUN ÉCHEC pour ${user.email}:`, mailgunError.message);
        console.error('   📌 Stack:', mailgunError.stack);
        
        // Fallback vers Nodemailer si Mailgun échoue
        try {
          console.log('   🔄 Tentative avec NODEMAILER (fallback)...');
          const mailOptions = {
            from: `"CCIS Souss Massa" <${process.env.EMAIL_HOST_USER}>`,
            to: user.email,
            subject: data.subject,
            html: data.body,
          };
          
          console.log('   📨 DONNÉES NODEMAILER:', JSON.stringify(mailOptions, null, 2));
          
          const nodemailerResult = await mail.sendMail(mailOptions);
          
          console.log(`   ✅ NODEMAILER SUCCÈS pour ${user.email}`);
          console.log('   📦 Réponse Nodemailer:', JSON.stringify(nodemailerResult, null, 2));
          
          results.success++;
          results.details.push({
            userId: user.id,
            email: user.email,
            status: 'success',
            service: 'nodemailer',
            messageId: nodemailerResult.messageId
          });
          
        } catch (nodemailerError: any) {
          console.error(`   ❌ NODEMAILER ÉCHEC pour ${user.email}:`, nodemailerError.message);
          results.failed++;
          results.details.push({
            userId: user.id,
            email: user.email,
            status: 'failed',
            service: 'both',
            error: nodemailerError.message
          });
        }
      }
    })
  );

  console.log('\n📊 ============ RÉSULTATS FINAUX ============');
  console.log(`✅ Succès: ${results.success}`);
  console.log(`❌ Échecs: ${results.failed}`);
  console.log(`📊 Total: ${results.total}`);
  console.log('🔍 Détails:', JSON.stringify(results.details, null, 2));
  console.log('📧 ============ FIN ENVOI EMAIL ============\n');

  return reply.code(200).send({
    message: `Emails envoyés: ${results.success} succès, ${results.failed} échecs`,
    results: results
  });
}
// -------------------------------------------------------------------------

export async function sendNotification(
  req: FastifyRequest<{ Body: NotificationSchema }>,
  reply: FastifyReply
) {
  const data = req.body;

  const users = await prisma.user.findMany({
    where: {
      id: { in: data.users },
      role: $Enums.Role.User,
    },
    select: { id: true },
  });

  await Promise.all(
    users.map(async (user) => {
      await prisma.notification.create({
        data: {
          title: "Message de l'administration",
          content: data.content,
          userId: user.id,
          source: $Enums.Source.Administration,
        },
      });
    })
  );

  return reply.code(200).send({});
}

// -------------------------------------------------------------------------

export async function sendSms(
  req: FastifyRequest<{ Body: SmsSchema }>,
  reply: FastifyReply
) {
  const data = req.body;

  const users = await prisma.user.findMany({
    where: {
      id: { in: data.users },
      role: $Enums.Role.User,
    },
    select: { id: true, phoneNumber: true },
  });

  if (users.length === 0) {
    return reply.code(400).send({ message: "Aucun utilisateur valide" });
  }

  const results = await Promise.all(users.map(async (u) => {
    const recipient = u.phoneNumber.startsWith("+212")
      ? u.phoneNumber.replace("+","")
      : (u.phoneNumber.startsWith("0") ? "212"+u.phoneNumber.slice(1) : u.phoneNumber);

    const res = await sendSmsAuto({
      recipient,
      content: data.content,
      senderId: process.env.SMS_SENDER_ID, // override possible
      userId: u.id
    });

    return { userId: u.id, recipient, ok: (res as any).ok === true };
  }));

  const okCount = results.filter(r => r.ok).length;
  const koCount = results.length - okCount;

  return reply.code(200).send({
    message: `SMS envoyés: ${okCount} succès, ${koCount} échec(s).`,
    details: results
  });
}
// -------------------------------------------------------------------------

export async function getUser(
  req: FastifyRequest<{ Params: IdParamsSchema }>,
  reply: FastifyReply
) {
  const id = req.params.id;

  const user = await prisma.user.findUnique({
    where: {
      id: id,
      role: $Enums.Role.User,
    },
    select: {
      id: true,
      civility: true,
      firstName: true,
      lastName: true,
      email: true,

      city: true,
      position: true,

      phoneNumber: true,

      expertiseAreas: true,
      interestAreas: true,
      bio: true,

      company: {
        select: {
          id: true,
          name: true,
        },
      },

      active: true,
      member: true,
      createdAt: true,
    },
  });

  if (!user) {
    return reply.code(404).send({
      message: "Cet utilisateur n'existe pas",
    });
  }

  return reply.code(200).send(user);
}

// -------------------------------------------------------------------------

export async function editUserActive(
  req: FastifyRequest<{ Params: IdParamsSchema; Body: UserActiveSchema }>,
  reply: FastifyReply
) {
  const id = req.params.id;
  const data = req.body;

  const user = await prisma.user.findUnique({
    where: {
      id: id,
      role: $Enums.Role.User,
    },
  });

  if (!user) {
    return reply.code(404).send({
      message: "Cet utilisateur n'existe pas",
    });
  }

  const newUser = await prisma.user.update({
    where: { id: id },
    data: {
      active: data.active,
    },
  });

  return reply
    .code(200)
    .send({ active: newUser.active, companyId: newUser.companyId });
}

// -------------------------------------------------------------------------

export async function editUserMember(
  req: FastifyRequest<{ Params: IdParamsSchema; Body: UserMemberSchema }>,
  reply: FastifyReply
) {
  const id = req.params.id;
  const data = req.body;

  const user = await prisma.user.findUnique({
    where: {
      id: id,
      role: $Enums.Role.User,
    },
  });

  if (!user) {
    return reply.code(404).send({
      message: "Cet utilisateur n'existe pas",
    });
  }

  const newUser = await prisma.user.update({
    where: { id: id },
    data: {
      member: data.member,
    },
  });

  return reply
    .code(200)
    .send({ member: newUser.member, companyId: newUser.companyId });
}

// -------------------------------------------------------------------------
