/**
 * PaymentTypeService - Gestion de Formas de Pago
 *
 * Administra las formas de pago del SAT para CFDI (PPD, PUE).
 *
 * @module Fiscal
 */

import { Repository } from 'typeorm';
import { PaymentType } from '../entities/payment-type.entity';

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

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

export interface CreatePaymentTypeDto {
  code: string;
  name: string;
  description?: string;
  isActive?: boolean;
}

export interface UpdatePaymentTypeDto extends Partial<CreatePaymentTypeDto> {}

export interface PaymentTypeFilters {
  isActive?: boolean;
  search?: string;
}

export class PaymentTypeService {
  private repository: Repository<PaymentType>;

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

  /**
   * Crear una nueva forma de pago
   */
  async create(_ctx: ServiceContext, data: CreatePaymentTypeDto): Promise<PaymentType> {
    const existing = await this.findByCode(data.code);
    if (existing) {
      throw new Error(`Payment type 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<PaymentType | null> {
    return this.repository.findOne({
      where: { id },
    });
  }

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

  /**
   * Actualizar forma de pago
   */
  async update(_ctx: ServiceContext, id: string, data: UpdatePaymentTypeDto): Promise<PaymentType | 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(`Payment type with code ${data.code} already exists`);
      }
    }

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

  /**
   * Desactivar forma de pago
   */
  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 formas de pago con filtros
   */
  async findWithFilters(
    _ctx: ServiceContext,
    filters: PaymentTypeFilters,
    page = 1,
    limit = 20
  ): Promise<PaginatedResult<PaymentType>> {
    const qb = this.repository.createQueryBuilder('pt');

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

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

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

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

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

  /**
   * Obtener todas las formas activas
   */
  async findAllActive(_ctx: ServiceContext): Promise<PaymentType[]> {
    return this.repository.find({
      where: { isActive: true },
      order: { code: 'ASC' },
    });
  }

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

    let activeCount = 0;
    for (const type of all) {
      if (type.isActive) activeCount++;
    }

    return {
      total: all.length,
      active: activeCount,
      inactive: all.length - activeCount,
    };
  }
}

export interface PaymentTypeStats {
  total: number;
  active: number;
  inactive: number;
}
