import { v4 as uuidv4 } from "uuid";
import { Inject } from "@nestjs/common";
import { ClassesRepository } from "./classes.repository.js";
import {
  ValidationError,
  NotFoundError,
} from "../shared/errors/application-error.js";
import type { CreateClassDto, UpdateClassDto } from "./classes.dto.js";
import type { Class, NewClass } from "./classes.schema.js";

export class ClassesService {
  constructor(
    @Inject(ClassesRepository) private readonly repository: ClassesRepository,
  ) {}

  async create(dto: CreateClassDto): Promise<Class> {
    const newClass: NewClass = {
      id: uuidv4(),
      ...dto,
    };
    return this.repository.create(newClass);
  }

  async getById(id: string): Promise<Class> {
    const result = await this.repository.findById(id);
    if (!result) {
      throw new NotFoundError("Class", id);
    }
    return result;
  }

  async list(gradeId?: string): Promise<Class[]> {
    return this.repository.list(gradeId);
  }

  async update(id: string, dto: UpdateClassDto): Promise<Class> {
    if (Object.keys(dto).length === 0) {
      throw new ValidationError("No fields to update");
    }
    const result = await this.repository.update(id, dto);
    if (!result) {
      throw new NotFoundError("Class", id);
    }
    return result;
  }

  async delete(id: string): Promise<void> {
    const existing = await this.repository.findById(id);
    if (!existing) {
      throw new NotFoundError("Class", id);
    }
    await this.repository.delete(id);
  }
}
