import {
  ConflictException,
  Inject,
  Injectable,
  NotFoundException,
} from "@nestjs/common";

import { PaginatedResponse } from "@edr/types";

import { CreateDropdownOptionDto } from "./dto/create-dropdown-option.dto";
import { CreateDropdownSettingDto } from "./dto/create-dropdown-setting.dto";
import { ListDropdownSettingsQueryDto } from "./dto/list-dropdown-settings-query.dto";
import { UpdateDropdownOptionDto } from "./dto/update-dropdown-option.dto";
import { UpdateDropdownSettingDto } from "./dto/update-dropdown-setting.dto";
import { DropdownOption } from "./entities/dropdown-option.entity";
import { DropdownSetting } from "./entities/dropdown-setting.entity";
import {
  DROPDOWN_SETTINGS_REPOSITORY,
  IDropdownSettingsRepository,
} from "./interfaces/dropdown-settings.repository.interface";

@Injectable()
export class DropdownSettingsService {
  constructor(
    @Inject(DROPDOWN_SETTINGS_REPOSITORY)
    private readonly repository: IDropdownSettingsRepository,
  ) {}

  list(): Promise<DropdownSetting[]> {
    return this.repository.findAll();
  }

  listPaged(
    query: ListDropdownSettingsQueryDto,
  ): Promise<PaginatedResponse<DropdownSetting>> {
    return this.repository.findPaged(query);
  }

  async getById(id: string): Promise<DropdownSetting> {
    const setting = await this.repository.findById(id);
    if (!setting) throw new NotFoundException(`Setting ${id} not found`);
    return setting;
  }

  async getByCode(code: string): Promise<DropdownSetting> {
    const setting = await this.repository.findByCode(code);
    if (!setting) throw new NotFoundException(`Setting "${code}" not found`);
    return setting;
  }

  async create(dto: CreateDropdownSettingDto): Promise<DropdownSetting> {
    const existing = await this.repository.findByCode(dto.code);
    if (existing) {
      throw new ConflictException(
        `Dropdown setting with code "${dto.code}" already exists`,
      );
    }

    const setting = await this.repository.create({
      code: dto.code,
      label: dto.label,
      description: dto.description ?? null,
      multiple: dto.multiple ?? false,
      meta: dto.meta ?? null,
    });

    if (dto.children && dto.children.length > 0) {
      await this.repository.replaceOptions(setting.id, dto.children);
    }

    return this.getById(setting.id);
  }

  async update(
    id: string,
    dto: UpdateDropdownSettingDto,
  ): Promise<DropdownSetting> {
    await this.getById(id);
    const updated = await this.repository.update(id, dto);
    if (!updated) throw new NotFoundException(`Setting ${id} not found`);
    return this.getById(id);
  }

  async remove(id: string): Promise<void> {
    await this.getById(id);
    await this.repository.softDelete(id);
  }

  /* ------------------------ option operations ------------------------ */

  async replaceOptions(
    settingId: string,
    options: CreateDropdownOptionDto[],
  ): Promise<DropdownOption[]> {
    await this.getById(settingId);
    return this.repository.replaceOptions(settingId, options);
  }

  async addOption(
    settingId: string,
    dto: CreateDropdownOptionDto,
  ): Promise<DropdownOption> {
    await this.getById(settingId);
    return this.repository.addOption(settingId, dto);
  }

  async updateOption(
    optionId: string,
    dto: UpdateDropdownOptionDto,
  ): Promise<DropdownOption> {
    const updated = await this.repository.updateOption(optionId, dto);
    if (!updated) throw new NotFoundException(`Option ${optionId} not found`);
    return updated;
  }

  async removeOption(optionId: string): Promise<void> {
    await this.repository.removeOption(optionId);
  }
}
