/**
 * BranchInventorySettings Service
 * Servicio para gestión de configuración de inventario por sucursal
 *
 * @module Branches
 */

import { Repository } from 'typeorm';
import { AppDataSource } from '../../../shared/database/typeorm.config';
import { BranchInventorySettings } from '../entities/branch-inventory-settings.entity';
import { ServiceContext } from './branch.service';

export interface CreateBranchInventorySettingsDto {
  branchId: string;
  warehouseId?: string;
  defaultStockMin?: number;
  defaultStockMax?: number;
  autoReorderEnabled?: boolean;
  priceListId?: string;
  allowPriceOverride?: boolean;
  maxDiscountPercent?: number;
  taxConfig?: Record<string, any>;
}

export interface UpdateBranchInventorySettingsDto {
  warehouseId?: string;
  defaultStockMin?: number;
  defaultStockMax?: number;
  autoReorderEnabled?: boolean;
  priceListId?: string;
  allowPriceOverride?: boolean;
  maxDiscountPercent?: number;
  taxConfig?: Record<string, any>;
}

export class BranchInventorySettingsService {
  private repository: Repository<BranchInventorySettings>;

  constructor() {
    this.repository = AppDataSource.getRepository(BranchInventorySettings);
  }

  async findByBranch(_ctx: ServiceContext, branchId: string): Promise<BranchInventorySettings | null> {
    return this.repository.findOne({
      where: { branchId },
      relations: ['branch'],
    });
  }

  async findById(_ctx: ServiceContext, id: string): Promise<BranchInventorySettings | null> {
    return this.repository.findOne({
      where: { id },
      relations: ['branch'],
    });
  }

  async findAll(_ctx: ServiceContext): Promise<BranchInventorySettings[]> {
    return this.repository.find({
      relations: ['branch'],
    });
  }

  async create(
    ctx: ServiceContext,
    data: CreateBranchInventorySettingsDto
  ): Promise<BranchInventorySettings> {
    // Check if settings already exist for this branch
    const existing = await this.findByBranch(ctx, data.branchId);
    if (existing) {
      throw new Error('Inventory settings already exist for this branch');
    }

    const settings = this.repository.create(data);
    return this.repository.save(settings);
  }

  async update(
    ctx: ServiceContext,
    id: string,
    data: UpdateBranchInventorySettingsDto
  ): Promise<BranchInventorySettings | null> {
    const settings = await this.findById(ctx, id);
    if (!settings) {
      return null;
    }

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

  async upsertByBranch(
    ctx: ServiceContext,
    branchId: string,
    data: UpdateBranchInventorySettingsDto
  ): Promise<BranchInventorySettings> {
    let settings = await this.findByBranch(ctx, branchId);

    if (settings) {
      Object.assign(settings, data);
    } else {
      settings = this.repository.create({
        branchId,
        ...data,
      });
    }

    return this.repository.save(settings);
  }

  async delete(_ctx: ServiceContext, id: string): Promise<boolean> {
    const result = await this.repository.delete({ id });
    return result.affected ? result.affected > 0 : false;
  }

  async deleteByBranch(_ctx: ServiceContext, branchId: string): Promise<boolean> {
    const result = await this.repository.delete({ branchId });
    return result.affected ? result.affected > 0 : false;
  }

  async getEffectiveSettings(
    ctx: ServiceContext,
    branchId: string
  ): Promise<{
    settings: BranchInventorySettings | null;
    defaults: UpdateBranchInventorySettingsDto;
  }> {
    const settings = await this.findByBranch(ctx, branchId);

    // Default values if no settings configured
    const defaults: UpdateBranchInventorySettingsDto = {
      defaultStockMin: 0,
      defaultStockMax: 1000,
      autoReorderEnabled: false,
      allowPriceOverride: false,
      maxDiscountPercent: 0,
      taxConfig: {},
    };

    return { settings, defaults };
  }
}
