/**
 * PaymentMethodService - Gestion de Metodos de Pago
 *
 * Administra los metodos de pago del SAT para CFDI.
 *
 * @module Fiscal
 */

import { Repository } from 'typeorm';
import { PaymentMethod } from '../entities/payment-method.entity';

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

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

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

export interface UpdatePaymentMethodDto extends Partial<CreatePaymentMethodDto> {}

export interface PaymentMethodFilters {
  requiresBankInfo?: boolean;
  isActive?: boolean;
  search?: string;
}

export class PaymentMethodService {
  private repository: Repository<PaymentMethod>;

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

  /**
   * Crear un nuevo metodo de pago
   */
  async create(_ctx: ServiceContext, data: CreatePaymentMethodDto): Promise<PaymentMethod> {
    const existing = await this.findByCode(data.code);
    if (existing) {
      throw new Error(`Payment method 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<PaymentMethod | null> {
    return this.repository.findOne({
      where: { id },
    });
  }

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

  /**
   * Actualizar metodo de pago
   */
  async update(_ctx: ServiceContext, id: string, data: UpdatePaymentMethodDto): Promise<PaymentMethod | 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 method with code ${data.code} already exists`);
      }
    }

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

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

    if (filters.requiresBankInfo !== undefined) {
      qb.andWhere('pm.requires_bank_info = :requiresBankInfo', {
        requiresBankInfo: filters.requiresBankInfo,
      });
    }

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

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

    const skip = (page - 1) * limit;
    qb.orderBy('pm.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 metodos activos
   */
  async findAllActive(_ctx: ServiceContext): Promise<PaymentMethod[]> {
    return this.repository.find({
      where: { isActive: true },
      order: { code: 'ASC' },
    });
  }

  /**
   * Obtener metodos que requieren informacion bancaria
   */
  async findRequiringBankInfo(_ctx: ServiceContext): Promise<PaymentMethod[]> {
    return this.repository.find({
      where: { isActive: true, requiresBankInfo: true },
      order: { code: 'ASC' },
    });
  }

  /**
   * Validar si un metodo de pago requiere info bancaria
   */
  async requiresBankInfo(_ctx: ServiceContext, code: string): Promise<boolean> {
    const method = await this.findByCode(code);
    return method?.requiresBankInfo ?? false;
  }

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

    let activeCount = 0;
    let requiresBankInfoCount = 0;

    for (const method of all) {
      if (method.isActive) activeCount++;
      if (method.requiresBankInfo) requiresBankInfoCount++;
    }

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

export interface PaymentMethodStats {
  total: number;
  active: number;
  inactive: number;
  requiresBankInfo: number;
}
