/**
 * FiscalRegimeService - Gestion de Regimenes Fiscales
 *
 * Administra los regimenes fiscales del SAT para emisores y receptores de CFDI.
 *
 * @module Fiscal
 */

import { Repository } from 'typeorm';
import { FiscalRegime, PersonType } from '../entities/fiscal-regime.entity';

interface ServiceContext {
  tenantId: string;
  userId?: string;
}

interface PaginatedResult<T> {
  data: T[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
}

export interface CreateFiscalRegimeDto {
  code: string;
  name: string;
  description?: string;
  appliesTo?: PersonType;
  isActive?: boolean;
}

export interface UpdateFiscalRegimeDto extends Partial<CreateFiscalRegimeDto> {}

export interface FiscalRegimeFilters {
  appliesTo?: PersonType;
  isActive?: boolean;
  search?: string;
}

export class FiscalRegimeService {
  private repository: Repository<FiscalRegime>;

  constructor(repository: Repository<FiscalRegime>) {
    this.repository = repository;
  }

  /**
   * Crear un nuevo regimen fiscal
   */
  async create(_ctx: ServiceContext, data: CreateFiscalRegimeDto): Promise<FiscalRegime> {
    const existing = await this.findByCode(data.code);
    if (existing) {
      throw new Error(`Fiscal regime with code ${data.code} already exists`);
    }

    const entity = this.repository.create({
      ...data,
      isActive: data.isActive ?? true,
    });
    return this.repository.save(entity);
  }

  /**
   * Buscar por ID
   */
  async findById(_ctx: ServiceContext, id: string): Promise<FiscalRegime | null> {
    return this.repository.findOne({
      where: { id },
    });
  }

  /**
   * Buscar por codigo
   */
  async findByCode(code: string): Promise<FiscalRegime | null> {
    return this.repository.findOne({
      where: { code },
    });
  }

  /**
   * Actualizar regimen fiscal
   */
  async update(_ctx: ServiceContext, id: string, data: UpdateFiscalRegimeDto): Promise<FiscalRegime | null> {
    const entity = await this.findById(_ctx, id);
    if (!entity) return null;

    if (data.code && data.code !== entity.code) {
      const existing = await this.findByCode(data.code);
      if (existing) {
        throw new Error(`Fiscal regime with code ${data.code} already exists`);
      }
    }

    Object.assign(entity, data);
    return this.repository.save(entity);
  }

  /**
   * Eliminar regimen fiscal (soft delete via isActive)
   */
  async deactivate(_ctx: ServiceContext, id: string): Promise<boolean> {
    const entity = await this.findById(_ctx, id);
    if (!entity) return false;
    entity.isActive = false;
    await this.repository.save(entity);
    return true;
  }

  /**
   * Buscar regimenes fiscales con filtros
   */
  async findWithFilters(
    _ctx: ServiceContext,
    filters: FiscalRegimeFilters,
    page = 1,
    limit = 20
  ): Promise<PaginatedResult<FiscalRegime>> {
    const qb = this.repository.createQueryBuilder('fr');

    if (filters.appliesTo) {
      qb.andWhere('(fr.applies_to = :appliesTo OR fr.applies_to = :both)', {
        appliesTo: filters.appliesTo,
        both: PersonType.BOTH,
      });
    }

    if (filters.isActive !== undefined) {
      qb.andWhere('fr.is_active = :isActive', { isActive: filters.isActive });
    }

    if (filters.search) {
      qb.andWhere('(fr.name ILIKE :search OR fr.code ILIKE :search OR fr.description ILIKE :search)', {
        search: `%${filters.search}%`,
      });
    }

    const skip = (page - 1) * limit;
    qb.orderBy('fr.code', 'ASC').skip(skip).take(limit);

    const [data, total] = await qb.getManyAndCount();

    return {
      data,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  /**
   * Obtener todos los regimenes activos
   */
  async findAllActive(_ctx: ServiceContext): Promise<FiscalRegime[]> {
    return this.repository.find({
      where: { isActive: true },
      order: { code: 'ASC' },
    });
  }

  /**
   * Obtener regimenes por tipo de persona
   */
  async findByPersonType(_ctx: ServiceContext, personType: PersonType): Promise<FiscalRegime[]> {
    const qb = this.repository
      .createQueryBuilder('fr')
      .where('fr.is_active = true')
      .andWhere('(fr.applies_to = :personType OR fr.applies_to = :both)', {
        personType,
        both: PersonType.BOTH,
      })
      .orderBy('fr.code', 'ASC');

    return qb.getMany();
  }

  /**
   * Obtener estadisticas
   */
  async getStats(_ctx: ServiceContext): Promise<FiscalRegimeStats> {
    const all = await this.repository.find();

    let naturalCount = 0;
    let legalCount = 0;
    let bothCount = 0;
    let activeCount = 0;

    for (const regime of all) {
      if (regime.isActive) activeCount++;
      switch (regime.appliesTo) {
        case PersonType.NATURAL:
          naturalCount++;
          break;
        case PersonType.LEGAL:
          legalCount++;
          break;
        case PersonType.BOTH:
          bothCount++;
          break;
      }
    }

    return {
      total: all.length,
      active: activeCount,
      inactive: all.length - activeCount,
      byPersonType: {
        natural: naturalCount,
        legal: legalCount,
        both: bothCount,
      },
    };
  }
}

export interface FiscalRegimeStats {
  total: number;
  active: number;
  inactive: number;
  byPersonType: {
    natural: number;
    legal: number;
    both: number;
  };
}
