import { ConflictException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { ILike } from 'typeorm';
import { generateCode } from '../../../common/utils/generate-code.util';
import { CreateServiceTypeDto } from '../dto/create-service-type.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateServiceTypeDto } from '../dto/update-service-type.dto';
import { ServiceType } from '../entities/service-type.entity';
import {
  IServiceTypesRepository,
  SERVICE_TYPES_REPOSITORY,
} from '../interfaces/service-types.repository.interface';
import { DisplayOrderService } from './display-order.service';

@Injectable()
export class ServiceTypesService {
  constructor(
    @Inject(SERVICE_TYPES_REPOSITORY)
    private readonly repository: IServiceTypesRepository,
    private readonly displayOrder: DisplayOrderService,
  ) {}

  /** List service types with pagination and optional filtering. */
  async findAll(filter: {
    isActive?: boolean;
    canBeBookedAlone?: boolean;
    search?: string;
    page?: number;
    pageSize?: number;
    sortBy?: string;
    sortOrder?: 'ASC' | 'DESC';
  }): Promise<{ data: ServiceType[]; meta: { total: number; page: number; pageSize: number; totalPages: number } }> {
    const page = filter.page ?? 1;
    const pageSize = filter.pageSize ?? 10;
    const where: Record<string, unknown> = {};
    if (filter.isActive !== undefined) where.isActive = filter.isActive;
    if (filter.canBeBookedAlone !== undefined) where.canBeBookedAlone = filter.canBeBookedAlone;
    if (filter.search) where.serviceName = ILike(`%${filter.search}%`);

    const [data, total] = await this.repository.findAndCount({
      where,
      order: { [filter.sortBy ?? 'displayOrder']: filter.sortOrder ?? 'ASC' },
      skip: (page - 1) * pageSize,
      take: pageSize,
    });
    return { data, meta: { total, page, pageSize, totalPages: Math.ceil(total / pageSize) } };
  }

  /** Get a single service type by ID. */
  async findById(id: string): Promise<ServiceType> {
    const entity = await this.repository.findById(id);
    if (!entity) throw new NotFoundException(`Service type ${id} not found`);
    return entity;
  }

  /** Get a service type by code. */
  async findByCode(code: string): Promise<ServiceType | null> {
    return this.repository.findByCode(code);
  }

  /** Create a new service type. */
  async create(dto: CreateServiceTypeDto): Promise<ServiceType> {
    const code = generateCode(dto.serviceName);
    const existing = await this.repository.findByCode(code);
    if (existing) throw new ConflictException(`Service type with name "${dto.serviceName}" conflicts with existing code "${code}"`);

    const displayOrder = await this.displayOrder.resolveCreateOrder(ServiceType, 'displayOrder', {
      explicitOrder: dto.displayOrder,
      insertAfterId: dto.insertAfterId,
    });

    return this.repository.create({
      code,
      serviceName: dto.serviceName,
      description: dto.description ?? null,
      canBeBookedAlone: dto.canBeBookedAlone ?? true,
      includesFirstMile: dto.includesFirstMile ?? false,
      includesLastMile: dto.includesLastMile ?? false,
      includesCustoms: dto.includesCustoms ?? false,
      priorityBonusPoints: dto.priorityBonusPoints ?? 0,
      isActive: dto.isActive ?? true,
      displayOrder,
    });
  }

  /** Update an existing service type. */
  async update(id: string, dto: UpdateServiceTypeDto): Promise<ServiceType> {
    await this.findById(id);
    const { ...patch } = dto;
    const updated = await this.repository.update(id, patch);
    if (!updated) throw new NotFoundException(`Service type ${id} not found`);
    return updated;
  }

  /** Soft-delete a service type. */
  async remove(id: string): Promise<void> {
    await this.findById(id);
    await this.repository.softDelete(id);
  }

  async reorder(dto: ReorderItemsDto): Promise<void> {
    await this.displayOrder.reorderByIds(ServiceType, 'displayOrder', dto.ids);
  }

  async moveOrder(id: string, direction: 'up' | 'down'): Promise<void> {
    await this.findById(id);
    await this.displayOrder.moveOne(ServiceType, 'displayOrder', id, direction);
  }
}
