import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { AppDataSource } from '../config/database';
import { Player } from '../models/Player';
import { PlayerGauges } from '../models/PlayerGauges';
import { PlayerBalances } from '../models/PlayerBalances';
import { PlayerHealth } from '../models/PlayerHealth';
import { PlayerAxes } from '../models/PlayerAxes';
import { PlayerSkills } from '../models/PlayerSkills';
import { generateTokens } from '../middleware/auth.middleware';
import { ENV } from '../config/env';
import { sendMail } from './mail.service';

const playerRepo = () => AppDataSource.getRepository(Player);

interface RegisterInput {
  username: string;
  email: string;
  password: string;
  language?: string;
  newsletter_optin?: boolean;
}

interface LoginInput {
  email: string;
  password: string;
}

export class AuthService {
  /**
   * Register new player with email/password
   */
  static async register(input: RegisterInput) {
    const repo = playerRepo();

    // Check existing
    const existingEmail = await repo.findOne({ where: { email: input.email } });
    if (existingEmail) throw new Error('Email déjà utilisé');

    const existingUsername = await repo.findOne({ where: { username: input.username } });
    if (existingUsername) throw new Error('Nom d\'utilisateur déjà pris');

    // Validate
    if (input.username.length < 3 || input.username.length > 50) {
      throw new Error('Le nom doit faire entre 3 et 50 caractères');
    }
    if (input.password.length < 8) {
      throw new Error('Le mot de passe doit faire au moins 8 caractères');
    }

    // Hash password
    const password_hash = await bcrypt.hash(input.password, 12);

    // Create UserAccount first (multi-character support)
    const { UserAccount } = await import('../models/UserAccount');
    const accountRepo = AppDataSource.getRepository(UserAccount);
    const account = accountRepo.create({
      email: input.email.toLowerCase(),
      dagaz: 0,
      lueurs: 0,
      total_purchased: 0,
      max_characters: 1,
      is_active: true,
    });
    const savedAccount = await accountRepo.save(account);

    // Create player linked to account
    const player = repo.create({
      username: input.username,
      email: input.email.toLowerCase(),
      password_hash,
      oauth_provider: 'email',
      language: (input.language || 'fr') as any,
      newsletter_optin: input.newsletter_optin || false,
      user_account_id: savedAccount.id,
    });

    const savedPlayer = await repo.save(player);

    // Initialize sub-entities
    await AuthService.initializePlayerData(savedPlayer.id);

    // Generate tokens
    const tokens = generateTokens(savedPlayer.id, false);

    return {
      player: AuthService.sanitizePlayer(savedPlayer),
      ...tokens,
    };
  }

  /**
   * Login with email/password
   */
  static async login(input: LoginInput) {
    const repo = playerRepo();

    const player = await repo.findOne({
      where: { email: input.email.toLowerCase() },
    });

    if (!player || !player.password_hash) {
      throw new Error('Email ou mot de passe incorrect');
    }

    const isValid = await bcrypt.compare(input.password, player.password_hash);
    if (!isValid) {
      throw new Error('Email ou mot de passe incorrect');
    }

    if (!player.is_active) {
      throw new Error('Compte désactivé');
    }

    // Update last login
    player.last_login = new Date();
    await repo.save(player);

    const tokens = generateTokens(player.id, player.is_admin, player.is_moderator);

    return {
      player: AuthService.sanitizePlayer(player),
      ...tokens,
    };
  }

  /**
   * OAuth login/register (Google, Facebook)
   */
  static async oauthLogin(provider: 'google' | 'facebook', profile: {
    id: string;
    email: string;
    name: string;
    picture?: string;
  }) {
    const repo = playerRepo();

    // Check if already linked
    let player = await repo.findOne({
      where: { oauth_provider: provider, oauth_id: profile.id },
    });

    if (!player) {
      // Check if email exists (link accounts)
      player = await repo.findOne({ where: { email: profile.email } });

      if (player) {
        // Link OAuth to existing account
        player.oauth_provider = provider;
        player.oauth_id = profile.id;
        if (profile.picture) player.profile_image_url = profile.picture;
        await repo.save(player);
      } else {
        // Create UserAccount first
        const { UserAccount } = await import('../models/UserAccount');
        const accountRepo = AppDataSource.getRepository(UserAccount);
        const account = accountRepo.create({
          email: profile.email,
          dagaz: 0, lueurs: 0, total_purchased: 0,
          max_characters: 1, is_active: true,
        });
        const savedAccount = await accountRepo.save(account);

        // Create new player linked to account
        const username = await AuthService.generateUniqueUsername(profile.name);
        player = repo.create({
          username,
          email: profile.email,
          oauth_provider: provider,
          oauth_id: profile.id,
          profile_image_url: profile.picture || null,
          password_hash: null,
          user_account_id: savedAccount.id,
        });
        player = await repo.save(player);
        await AuthService.initializePlayerData(player.id);
      }
    }

    player.last_login = new Date();
    await repo.save(player);

    const tokens = generateTokens(player.id, player.is_admin, player.is_moderator);

    return {
      player: AuthService.sanitizePlayer(player),
      ...tokens,
    };
  }

  /**
   * Get player profile by ID
   */
  static async getProfile(playerId: string) {
    const player = await playerRepo().findOne({
      where: { id: playerId },
      relations: ['gauges', 'balances'],
    });
    if (!player) throw new Error('Joueur introuvable');
    const safe = AuthService.sanitizePlayer(player);
    const { enrichPlayerForMap } = await import('../utils/player-dto');
    return enrichPlayerForMap(safe);
  }

  /**
   * Initialize all player sub-data (gauges, skills, axes, balances, health)
   */
  private static async initializePlayerData(playerId: string) {
    // Gauges (default values - will be adjusted by onboarding)
    const gauges = new PlayerGauges();
    gauges.player_id = playerId;
    gauges.fortune = 0;
    gauges.pouvoir = 5;
    gauges.chaleur = 0;
    gauges.conscience = 50;
    gauges.respect = 5;
    gauges.social = 10;
    gauges.popularite = 0;
    gauges.instabilite = 20;
    gauges.influence = 0;
    gauges.ecologie = 50;
    // Phase 8 v2 (2026-05-01) — sante_physique retirée (single source
    // physical_health sur player_health, default DB = 100, créé ci-dessous
    // dans la section "Health"). La colonne sera droppée en migration 071.
    gauges.sit_score = 0;
    await AppDataSource.getRepository(PlayerGauges).save(gauges);

    // Balances (start with 0)
    const balances = new PlayerBalances();
    balances.player_id = playerId;
    balances.infinite_light = 0;
    balances.infinite_shadow = 0;
    balances.dagaz = 0;
    balances.quintessence = 0;
    await AppDataSource.getRepository(PlayerBalances).save(balances);

    // Health
    const health = new PlayerHealth();
    health.player_id = playerId;
    await AppDataSource.getRepository(PlayerHealth).save(health);

    // 22 Axes (all start at 0, set during onboarding)
    const axesRepo = AppDataSource.getRepository(PlayerAxes);
    const axesArray: PlayerAxes[] = [];
    for (let i = 1; i <= 22; i++) {
      const axis = new PlayerAxes();
      axis.player_id = playerId;
      axis.axis_id = i;
      axis.value = 0;
      axesArray.push(axis);
    }
    await axesRepo.save(axesArray);

    // 16 Skills (all start at 0)
    const skillsRepo = AppDataSource.getRepository(PlayerSkills);
    const skillsArray: PlayerSkills[] = [];
    for (let i = 1; i <= 16; i++) {
      const skill = new PlayerSkills();
      skill.player_id = playerId;
      skill.skill_id = i;
      skill.level = 0;
      skill.experience = 0;
      skillsArray.push(skill);
    }
    await skillsRepo.save(skillsArray);
  }

  /**
   * Generate unique username from OAuth name
   */
  private static async generateUniqueUsername(name: string): Promise<string> {
    const base = name.replace(/[^a-zA-Z0-9]/g, '').substring(0, 15);
    let username = base;
    let counter = 1;
    const repo = playerRepo();

    while (await repo.findOne({ where: { username } })) {
      username = `${base}${counter}`;
      counter++;
    }

    return username;
  }

  /**
   * Request password reset: generate token and send email
   */
  static async requestPasswordReset(email: string) {
    const repo = playerRepo();
    const player = await repo.findOne({ where: { email: email.toLowerCase() } });

    // If player exists and has a password (email auth), send reset email
    if (player && player.password_hash) {
      const resetToken = jwt.sign(
        { id: player.id, type: 'password-reset' },
        ENV.JWT_SECRET,
        { expiresIn: 3600 } // 1h in seconds
      );

      const resetLink = `${ENV.FRONTEND_URL}/reset-password?token=${resetToken}`;

      await sendMail({
        to: player.email,
        subject: 'Réinitialisation de votre mot de passe - Ombres & Lumières',
        html: `
          <h2>Réinitialisation de mot de passe</h2>
          <p>Bonjour ${player.username},</p>
          <p>Vous avez demandé la réinitialisation de votre mot de passe.</p>
          <p>Cliquez sur le lien ci-dessous pour définir un nouveau mot de passe :</p>
          <p><a href="${resetLink}" style="display:inline-block;padding:12px 28px;background:linear-gradient(135deg,#8b1a1a,#c41e1e);color:white;text-decoration:none;border-radius:6px;font-weight:bold;">Réinitialiser mon mot de passe</a></p>
          <p>Ce lien expire dans 1 heure.</p>
          <p>Si vous n'avez pas fait cette demande, ignorez cet email.</p>
        `,
      });
    }

    // Always return same message for security (don't reveal if email exists)
  }

  /**
   * Confirm password reset: verify token and update password
   */
  static async confirmPasswordReset(token: string, newPassword: string) {
    // Verify token
    let decoded: { id: string; type: string };
    try {
      decoded = jwt.verify(token, ENV.JWT_SECRET) as { id: string; type: string };
    } catch (err) {
      throw new Error('Token invalide ou expiré');
    }

    if (decoded.type !== 'password-reset') {
      throw new Error('Token invalide');
    }

    // Validate new password
    if (newPassword.length < 8) {
      throw new Error('Le mot de passe doit faire au moins 8 caractères');
    }

    const repo = playerRepo();
    const player = await repo.findOne({ where: { id: decoded.id } });

    if (!player) {
      throw new Error('Joueur introuvable');
    }

    // Hash and update password
    player.password_hash = await bcrypt.hash(newPassword, 12);
    await repo.save(player);
  }

  /**
   * Refresh token: verify refresh token and return new token pair
   */
  static async refreshToken(refreshToken: string) {
    let decoded: { id: string; isAdmin: boolean; isModerator: boolean; type: string };
    try {
      decoded = jwt.verify(refreshToken, ENV.JWT_REFRESH_SECRET) as any;
    } catch (err) {
      throw new Error('Refresh token invalide ou expiré');
    }

    if (decoded.type !== 'refresh') {
      throw new Error('Token invalide');
    }

    // Verify player still exists and is active
    const repo = playerRepo();
    const player = await repo.findOne({ where: { id: decoded.id } });

    if (!player) {
      throw new Error('Joueur introuvable');
    }

    if (!player.is_active) {
      throw new Error('Compte désactivé');
    }

    // Generate new token pair
    return generateTokens(player.id, player.is_admin, player.is_moderator);
  }

  /**
   * Remove sensitive fields from player object
   */
  private static sanitizePlayer(player: Player) {
    const { password_hash, oauth_id, ...safe } = player as any;
    return safe;
  }
}
