import { AppDataSource } from '../config/database';
import { Employment, EmploymentSchedule } from '../models/Employment';
import { PlayerBalances } from '../models/PlayerBalances';
import { Player } from '../models/Player';
import { PlayerSkills } from '../models/PlayerSkills';
import { PoliceFile } from '../models/PoliceFile';
import { MissionProgress } from '../models/MissionProgress';
import { EMPLOYMENTS, EmploymentDefinition, MAX_ACTIVE_JOBS } from '../constants/employment';
import { TransactionService } from './transaction.service';

const employmentRepo = () => AppDataSource.getRepository(Employment);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const playerRepo = () => AppDataSource.getRepository(Player);

export class EmploymentService {

  /** List available job types from constants (for journal/phone ads) */
  static getJobCatalog(): EmploymentDefinition[] {
    return EMPLOYMENTS;
  }

  /** Get ALL active jobs for a player (up to 3) */
  static async getActiveJobs(playerId: string): Promise<Employment[]> {
    return employmentRepo().find({
      where: { player_id: playerId, is_active: true },
      order: { hired_at: 'ASC' },
    });
  }

  /** Get player's single active job (legacy compat — returns first active) */
  static async getActiveJob(playerId: string): Promise<Employment | null> {
    return employmentRepo().findOne({
      where: { player_id: playerId, is_active: true },
    });
  }

  /** Get player's employment history */
  static async getHistory(playerId: string) {
    return employmentRepo().find({
      where: { player_id: playerId },
      order: { created_at: 'DESC' },
    });
  }

  /** Check if a player meets the prerequisites for a job type */
  static async checkPrerequisites(playerId: string, jobType: string): Promise<{ eligible: boolean; reason?: string }> {
    const def = EMPLOYMENTS.find(e => e.type === jobType);
    if (!def) return { eligible: false, reason: 'Type d\'emploi invalide' };

    const prereq = def.prerequisites;

    // Check max active jobs
    const activeJobs = await employmentRepo().find({ where: { player_id: playerId, is_active: true } });
    if (activeJobs.length >= MAX_ACTIVE_JOBS) {
      return { eligible: false, reason: `Maximum ${MAX_ACTIVE_JOBS} emplois simultanes atteint` };
    }

    // Check not already employed for this type
    if (activeJobs.some(j => j.type === jobType)) {
      return { eligible: false, reason: 'Vous exercez deja cet emploi' };
    }

    // Check total payslips from all jobs
    if (prereq.min_payslips) {
      const history = await employmentRepo().find({ where: { player_id: playerId } });
      const totalPayslips = history.reduce((sum, j) => sum + (j.total_payslips || 0), 0);
      if (totalPayslips < prereq.min_payslips) {
        return { eligible: false, reason: `${prereq.min_payslips} fiches de paie requises (vous en avez ${totalPayslips})` };
      }
    }

    // Check multi-skill requirements
    if (prereq.skills && prereq.skills.length > 0) {
      const skillRepo = AppDataSource.getRepository(PlayerSkills);
      for (const req of prereq.skills) {
        const skill = await skillRepo.findOne({
          where: { player_id: playerId, skill_id: req.skill_id },
        });
        const { SKILL_DEFINITIONS } = await import('../models/PlayerSkills');
        const skillName = SKILL_DEFINITIONS[req.skill_id]?.name || `Skill #${req.skill_id}`;
        if (!skill || skill.level < req.min_level) {
          const current = skill?.level ?? 0;
          return { eligible: false, reason: `${skillName} niveau ${req.min_level} requis (vous avez ${current})` };
        }
      }
    }

    // Check casier judiciaire (police degree)
    if (prereq.requires_clean_record) {
      const policeFile = await AppDataSource.getRepository(PoliceFile).findOneBy({ player_id: playerId });
      if (policeFile && policeFile.degree > 0) {
        return { eligible: false, reason: 'Casier judiciaire vierge requis pour ce poste' };
      }
    }
    if (prereq.max_police_degree !== undefined) {
      const policeFile = await AppDataSource.getRepository(PoliceFile).findOneBy({ player_id: playerId });
      if (policeFile && policeFile.degree > prereq.max_police_degree) {
        return { eligible: false, reason: `Votre casier judiciaire est trop charge pour ce poste (max degre ${prereq.max_police_degree})` };
      }
    }

    // Check vehicle requirement
    if (prereq.requires_vehicle) {
      const { Vehicle } = await import('../models/Vehicle');
      const vehicleCount = await AppDataSource.getRepository(Vehicle).count({
        where: { player_id: playerId },
      });
      if (vehicleCount === 0) {
        return { eligible: false, reason: 'Un vehicule est requis pour ce poste' };
      }
    }

    // Check business requirement
    if (prereq.requires_business) {
      const { Business } = await import('../models/Business');
      const bizCount = await AppDataSource.getRepository(Business).count({
        where: { player_id: playerId },
      });
      if (bizCount === 0) {
        return { eligible: false, reason: 'Vous devez posseder au moins un business' };
      }
    }

    return { eligible: true };
  }

  /** Direct hire (legacy compat — used by onboarding StepFirstJob) */
  static async hire(playerId: string, data: {
    type: string;
    employer_name: string;
    schedule?: EmploymentSchedule;
  }) {
    const def = EMPLOYMENTS.find(e => e.type === data.type);
    if (!def) throw new Error('Type d\'emploi invalide');

    const player = await playerRepo().findOne({ where: { id: playerId } });
    const baseLat = Number(player?.current_lat ?? player?.start_lat ?? 48.8566);
    const baseLon = Number(player?.current_lon ?? player?.start_lon ?? 2.3522);

    const employment = employmentRepo().create({
      player_id: playerId,
      type: data.type,
      employer_name: data.employer_name || def.employer_name,
      schedule: data.schedule || 'full_time',
      hourly_rate: def.hourly_rate,
      maintenance_per_day: def.maintenance_per_day,
      min_hours: def.min_hours,
      max_hours: def.max_hours,
      payslips_for_loan: 5,
      is_cdi: false,
      hired_at: new Date(),
      is_active: true,
      work_location_lat: baseLat + (Math.random() - 0.5) * 0.005,
      work_location_lon: baseLon + (Math.random() - 0.5) * 0.005,
    });

    return employmentRepo().save(employment);
  }

  /** Apply for a job (checks prerequisites then hires) */
  static async apply(playerId: string, jobType: string): Promise<Employment> {
    const check = await EmploymentService.checkPrerequisites(playerId, jobType);
    if (!check.eligible) throw new Error(check.reason || 'Prerequis non remplis');

    const def = EMPLOYMENTS.find(e => e.type === jobType);
    if (!def) throw new Error('Type d\'emploi invalide');

    const player = await playerRepo().findOne({ where: { id: playerId } });
    const baseLat = Number(player?.current_lat ?? player?.start_lat ?? 48.8566);
    const baseLon = Number(player?.current_lon ?? player?.start_lon ?? 2.3522);

    const employment = employmentRepo().create({
      player_id: playerId,
      type: jobType,
      employer_name: def.employer_name,
      schedule: 'full_time',
      hourly_rate: def.hourly_rate,
      maintenance_per_day: def.maintenance_per_day,
      min_hours: def.min_hours,
      max_hours: def.max_hours,
      payslips_for_loan: 5,
      is_cdi: false,
      hired_at: new Date(),
      is_active: true,
      work_location_lat: baseLat + (Math.random() - 0.5) * 0.005,
      work_location_lon: baseLon + (Math.random() - 0.5) * 0.005,
    });

    return employmentRepo().save(employment);
  }

  /** Quit a specific job by ID */
  static async quit(playerId: string, jobId?: string) {
    let job: Employment | null;
    if (jobId) {
      job = await employmentRepo().findOne({ where: { id: jobId, player_id: playerId, is_active: true } });
    } else {
      // Legacy: quit first active job
      job = await employmentRepo().findOne({ where: { player_id: playerId, is_active: true } });
    }
    if (!job) throw new Error('Aucun emploi actif');
    if (job.is_working) throw new Error('Impossible de demissionner pendant un shift');

    job.is_active = false;
    return employmentRepo().save(job);
  }

  /**
   * Start a work session for a SPECIFIC job.
   * Checks: not already working elsewhere, not in mission, not hospitalized/imprisoned/in transit.
   */
  static async startWork(playerId: string, jobId: string, durationHours: number): Promise<Employment> {
    const job = await employmentRepo().findOne({
      where: { id: jobId, player_id: playerId, is_active: true },
    });
    if (!job) throw new Error('Emploi introuvable');
    if (job.is_working) throw new Error('Vous etes deja au travail pour cet emploi');

    // Check duration bounds
    if (durationHours < job.min_hours || durationHours > job.max_hours) {
      throw new Error(`Duree de travail pour ${job.type}: ${job.min_hours}h a ${job.max_hours}h`);
    }

    // Check not already working in ANY other job
    const otherWorking = await employmentRepo().findOne({
      where: { player_id: playerId, is_active: true, is_working: true },
    });
    if (otherWorking) {
      throw new Error('Vous etes deja au travail dans un autre emploi. Un seul shift a la fois.');
    }

    // Check player state
    const player = await playerRepo().findOne({ where: { id: playerId } });
    if (!player) throw new Error('Joueur introuvable');
    if (player.in_transit) throw new Error('Vous etes en deplacement');

    const { PlayerHealth } = await import('../models/PlayerHealth');
    const health = await AppDataSource.getRepository(PlayerHealth).findOneBy({ player_id: playerId });
    if (health?.hospitalized_until && new Date(health.hospitalized_until) > new Date()) {
      throw new Error('Impossible de travailler pendant une hospitalisation');
    }
    if (health?.imprisoned_until && new Date(health.imprisoned_until) > new Date()) {
      throw new Error('Impossible de travailler pendant une incarceration');
    }

    // Check not in a mission (player_participates + in_progress)
    const missionRepo = AppDataSource.getRepository(MissionProgress);
    const activeMission = await missionRepo.findOne({
      where: { player_id: playerId, status: 'in_progress' as any, player_participates: true },
    });
    if (activeMission) {
      throw new Error('Impossible de travailler pendant une mission en cours');
    }

    const now = new Date();
    job.is_working = true;
    job.work_started_at = now;
    job.work_ends_at = new Date(now.getTime() + durationHours * 60 * 60 * 1000);

    return employmentRepo().save(job);
  }

  /**
   * End a work session (called by CRON or manually).
   * Pays hourly_rate * hours_worked in I-lumiere.
   */
  static async endWork(playerId: string): Promise<{ paid: number; hours: number }> {
    const job = await employmentRepo().findOne({
      where: { player_id: playerId, is_active: true, is_working: true },
    });
    if (!job) throw new Error('Pas en cours de travail');

    const hourlyRate = job.hourly_rate;

    // Calculate actual hours worked
    const startTime = job.work_started_at ? new Date(job.work_started_at).getTime() : Date.now();
    const hoursWorked = Math.min(job.max_hours, Math.max(1, Math.round((Date.now() - startTime) / (60 * 60 * 1000))));
    const payment = hourlyRate * hoursWorked;

    // Pay the player in I-lumiere
    await balancesRepo().increment({ player_id: playerId }, 'infinite_light', payment);
    await TransactionService.log({
      player_id: playerId,
      category: 'employment',
      type: 'in',
      amount: payment,
      currency: 'infinite_light',
      description: `Salaire ${hoursWorked}h — ${job.type} (${hourlyRate}∞/h)`,
    });

    // Update employment
    job.is_working = false;
    job.work_started_at = null;
    job.work_ends_at = null;
    job.hours_worked_today += hoursWorked;
    job.total_hours_worked += hoursWorked;

    // Increment payslips (1 payslip per 8h worked)
    if (job.total_hours_worked >= (job.total_payslips + 1) * 8) {
      job.total_payslips += 1;
      if (!job.is_cdi && job.total_payslips >= job.payslips_for_loan) {
        job.is_cdi = true;
      }
    }

    await employmentRepo().save(job);

    // Move player back to residence (if they have one)
    const { Residence } = await import('../models/Residence');
    const residence = await AppDataSource.getRepository(Residence).findOne({
      where: { player_id: playerId, is_main_residence: true },
    });
    if (residence?.location_lat && residence?.location_lon) {
      await playerRepo().update(playerId, {
        current_lat: residence.location_lat,
        current_lon: residence.location_lon,
        in_transit: false,
      });
    }

    return { paid: payment, hours: hoursWorked };
  }

  /** Check and auto-end expired work sessions (called every 60s by CRON) */
  static async resolveExpiredWorkSessions(): Promise<number> {
    const now = new Date();
    const expired = await employmentRepo()
      .createQueryBuilder('e')
      .where('e.is_working = true')
      .andWhere('e.work_ends_at <= :now', { now })
      .getMany();

    let resolved = 0;
    for (const job of expired) {
      try {
        await EmploymentService.endWork(job.player_id);
        resolved++;
      } catch (err) {
        console.error(`[EMPLOYMENT] Failed to end work for ${job.player_id}:`, (err as Error).message);
      }
    }
    return resolved;
  }

  /** Check if player is currently working (for mission lock) */
  static async isWorking(playerId: string): Promise<boolean> {
    const job = await employmentRepo().findOne({
      where: { player_id: playerId, is_active: true, is_working: true },
    });
    return !!job;
  }

  /** Process daily maintenance costs for all active employments */
  static async processDailyPayslips() {
    const activeJobs = await employmentRepo().find({ where: { is_active: true } });
    let processed = 0;

    for (const job of activeJobs) {
      const today = new Date().toISOString().slice(0, 10);
      const lastUpdate = job.updated_at.toISOString().slice(0, 10);
      if (lastUpdate === today) continue;

      // Deduct daily maintenance only (no automatic salary — salary is paid when work ends)
      if (job.maintenance_per_day > 0) {
        const balance = await balancesRepo().findOne({ where: { player_id: job.player_id } });
        if (!balance) continue;
        const debit = Math.min(job.maintenance_per_day, Number(balance.infinite_light));
        if (debit > 0) {
          await balancesRepo().decrement({ player_id: job.player_id }, 'infinite_light', debit);
          await TransactionService.log({
            player_id: job.player_id,
            category: 'employment',
            type: 'out',
            amount: debit,
            currency: 'infinite_light',
            description: `Frais emploi (${job.type})`,
          });
        }
      }

      // Reset daily hours
      job.hours_worked_today = 0;
      await employmentRepo().save(job);
      processed++;
    }

    return { processed, total: activeJobs.length };
  }
}
