import {
  Injectable,
  ConflictException,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import { ServiceTypeRepository } from './repositories/service-type.repository';
import { CreateServiceTypeDto, UpdateServiceTypeDto } from './dto';
import { serviceMessages } from '../../common/constants/messages';

const MSG = serviceMessages('Service type');

@Injectable()
export class ServiceTypeService {
  constructor(private readonly repo: ServiceTypeRepository) {}

  async findAll(query?: { page?: number; limit?: number; search?: string }) {
    return this.repo.findPaginated({
      page: query?.page,
      limit: query?.limit,
      search: query?.search,
      searchColumns: ['name', 'code'],
      relations: [],
      order: { sort_order: 'ASC', name: 'ASC' },
    });
  }

  async findAllActive() {
    return this.repo.findAllActive();
  }

  async findById(id: string) {
    const item = await this.repo.findById(id);
    if (!item) throw new NotFoundException(MSG.NOT_FOUND);
    return item;
  }

  async create(dto: CreateServiceTypeDto) {
    const existing = await this.repo.findByCode(dto.code);
    if (existing) throw new ConflictException(MSG.ALREADY_EXISTS('code'));

    const item = await this.repo.save({
      name: dto.name,
      code: dto.code,
      description: dto.description || null,
      is_active: dto.is_active !== undefined ? dto.is_active : true,
      is_system: false,
    });

    return { id: item.id, message: MSG.CREATED };
  }

  async update(id: string, dto: UpdateServiceTypeDto) {
    const item = await this.repo.findById(id);
    if (!item) throw new NotFoundException(MSG.NOT_FOUND);

    if (dto.code && dto.code !== item.code) {
      const existing = await this.repo.findByCode(dto.code);
      if (existing) throw new ConflictException(MSG.ALREADY_EXISTS('code'));
    }

    const updateData: any = {};
    if (dto.name !== undefined) updateData.name = dto.name;
    if (dto.code !== undefined) updateData.code = dto.code;
    if (dto.description !== undefined) updateData.description = dto.description;
    if (dto.is_active !== undefined) updateData.is_active = dto.is_active;

    await this.repo.update(id, updateData);
    return { id, message: MSG.UPDATED };
  }

  async reorder(items: { id: string; sort_order: number }[]) {
    for (const item of items) {
      await this.repo.update(item.id, { sort_order: item.sort_order });
    }
  }

  async remove(id: string) {
    const item = await this.repo.findById(id);
    if (!item) throw new NotFoundException(MSG.NOT_FOUND);
    if (item.is_system) throw new BadRequestException(MSG.CANNOT_DELETE_SYSTEM);

    await this.repo.softDelete(id);
    return { message: MSG.DELETED };
  }
}
