/**
 * @ai-summary Business logic for ownership costs feature
 * @ai-context Handles ownership cost operations and TCO aggregation
 */

import { Pool } from 'pg';
import { OwnershipCostsRepository } from '../data/ownership-costs.repository';
import {
  OwnershipCost,
  CreateOwnershipCostRequest,
  UpdateOwnershipCostRequest,
  OwnershipCostResponse,
  OwnershipCostStats,
  PAYMENTS_PER_YEAR,
  OwnershipCostType
} from './ownership-costs.types';
import { logger } from '../../../core/logging/logger';
import { VehiclesRepository } from '../../vehicles/data/vehicles.repository';

export class OwnershipCostsService {
  private repository: OwnershipCostsRepository;
  private vehiclesRepository: VehiclesRepository;

  constructor(pool: Pool) {
    this.repository = new OwnershipCostsRepository(pool);
    this.vehiclesRepository = new VehiclesRepository(pool);
  }

  async create(data: CreateOwnershipCostRequest, userId: string): Promise<OwnershipCostResponse> {
    logger.info('Creating ownership cost', { userId, vehicleId: data.vehicleId, costType: data.costType });

    // Verify vehicle ownership
    const vehicle = await this.vehiclesRepository.findById(data.vehicleId);
    if (!vehicle) {
      throw new Error('Vehicle not found');
    }
    if (vehicle.userId !== userId) {
      throw new Error('Unauthorized');
    }

    const cost = await this.repository.create({ ...data, userId });
    return this.toResponse(cost);
  }

  async getByVehicleId(vehicleId: string, userId: string): Promise<OwnershipCostResponse[]> {
    // Verify vehicle ownership
    const vehicle = await this.vehiclesRepository.findById(vehicleId);
    if (!vehicle) {
      throw new Error('Vehicle not found');
    }
    if (vehicle.userId !== userId) {
      throw new Error('Unauthorized');
    }

    const costs = await this.repository.findByVehicleId(vehicleId, userId);
    return costs.map(cost => this.toResponse(cost));
  }

  async getById(id: string, userId: string): Promise<OwnershipCostResponse> {
    const cost = await this.repository.findById(id);

    if (!cost) {
      throw new Error('Ownership cost not found');
    }

    if (cost.userId !== userId) {
      throw new Error('Unauthorized');
    }

    return this.toResponse(cost);
  }

  async update(id: string, data: UpdateOwnershipCostRequest, userId: string): Promise<OwnershipCostResponse> {
    // Verify ownership
    const existing = await this.repository.findById(id);
    if (!existing) {
      throw new Error('Ownership cost not found');
    }
    if (existing.userId !== userId) {
      throw new Error('Unauthorized');
    }

    const updated = await this.repository.update(id, data);
    if (!updated) {
      throw new Error('Update failed');
    }

    return this.toResponse(updated);
  }

  async delete(id: string, userId: string): Promise<void> {
    // Verify ownership
    const existing = await this.repository.findById(id);
    if (!existing) {
      throw new Error('Ownership cost not found');
    }
    if (existing.userId !== userId) {
      throw new Error('Unauthorized');
    }

    await this.repository.delete(id);
    logger.info('Ownership cost deleted', { id, userId });
  }

  /**
   * Get aggregated cost statistics for a vehicle
   * Used by TCO calculation in vehicles service
   */
  async getVehicleCostStats(vehicleId: string, userId: string): Promise<OwnershipCostStats> {
    const costs = await this.repository.findByVehicleId(vehicleId, userId);
    const now = new Date();

    const stats: OwnershipCostStats = {
      insuranceCosts: 0,
      registrationCosts: 0,
      taxCosts: 0,
      otherCosts: 0,
      totalCosts: 0
    };

    for (const cost of costs) {
      const startDate = new Date(cost.startDate);
      const endDate = cost.endDate ? new Date(cost.endDate) : now;

      // Skip future costs
      if (startDate > now) continue;

      // Calculate effective end date (either specified end, or now for ongoing costs)
      const effectiveEnd = endDate < now ? endDate : now;
      const monthsCovered = this.calculateMonthsBetween(startDate, effectiveEnd);
      const normalizedCost = this.normalizeToTotal(cost.amount, cost.interval, monthsCovered);

      // Type-safe key access
      const keyMap: Record<OwnershipCostType, keyof Omit<OwnershipCostStats, 'totalCosts'>> = {
        insurance: 'insuranceCosts',
        registration: 'registrationCosts',
        tax: 'taxCosts',
        other: 'otherCosts'
      };

      const key = keyMap[cost.costType];
      if (key) {
        stats[key] += normalizedCost;
      } else {
        logger.warn('Unknown cost type in aggregation', { costType: cost.costType, costId: cost.id });
      }
    }

    stats.totalCosts = stats.insuranceCosts + stats.registrationCosts + stats.taxCosts + stats.otherCosts;
    return stats;
  }

  /**
   * Calculate months between two dates
   */
  private calculateMonthsBetween(startDate: Date, endDate: Date): number {
    const yearDiff = endDate.getFullYear() - startDate.getFullYear();
    const monthDiff = endDate.getMonth() - startDate.getMonth();
    return Math.max(1, yearDiff * 12 + monthDiff);
  }

  /**
   * Normalize recurring cost to total based on interval and months covered
   */
  private normalizeToTotal(amount: number, interval: string, monthsCovered: number): number {
    // One-time costs are just the amount
    if (interval === 'one_time') {
      return amount;
    }

    const paymentsPerYear = PAYMENTS_PER_YEAR[interval as keyof typeof PAYMENTS_PER_YEAR];
    if (!paymentsPerYear) {
      logger.warn('Invalid cost interval', { interval });
      return 0;
    }

    // Calculate total payments over the covered period
    const yearsOwned = monthsCovered / 12;
    const totalPayments = yearsOwned * paymentsPerYear;
    return amount * totalPayments;
  }

  private toResponse(cost: OwnershipCost): OwnershipCostResponse {
    return {
      id: cost.id,
      userId: cost.userId,
      vehicleId: cost.vehicleId,
      documentId: cost.documentId,
      costType: cost.costType,
      description: cost.description,
      amount: cost.amount,
      interval: cost.interval,
      startDate: cost.startDate instanceof Date ? cost.startDate.toISOString().split('T')[0] : cost.startDate as unknown as string,
      endDate: cost.endDate ? (cost.endDate instanceof Date ? cost.endDate.toISOString().split('T')[0] : cost.endDate as unknown as string) : undefined,
      createdAt: cost.createdAt instanceof Date ? cost.createdAt.toISOString() : cost.createdAt as unknown as string,
      updatedAt: cost.updatedAt instanceof Date ? cost.updatedAt.toISOString() : cost.updatedAt as unknown as string,
    };
  }
}
