import { Injectable, OnModuleInit, ConflictException, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Designation, DesignationDocument } from './designation.schema';

const DEFAULT_DESIGNATIONS = ['Teaching Staff', 'Non Teaching Staff'];

@Injectable()
export class DesignationsService implements OnModuleInit {
    private readonly logger = new Logger(DesignationsService.name);

    constructor(
        @InjectModel(Designation.name)
        private readonly designationModel: Model<DesignationDocument>,
    ) {}

    async onModuleInit() {
        await this.seedDefaults();
    }

    private async seedDefaults() {
        for (const name of DEFAULT_DESIGNATIONS) {
            const exists = await this.designationModel
                .findOne({ name })
                .collation({ locale: 'en', strength: 2 })
                .lean();
            if (!exists) {
                await this.designationModel.create({ name, isDefault: true });
                this.logger.log(`Seeded default designation: ${name}`);
            }
        }
    }

    async findAll(): Promise<Designation[]> {
        return this.designationModel.find().sort({ isDefault: -1, name: 1 }).lean();
    }

    async create(name: string): Promise<Designation> {
        const trimmed = name.trim();
        if (!trimmed) {
            throw new ConflictException('Designation name is required');
        }

        const existing = await this.designationModel
            .findOne({ name: trimmed })
            .collation({ locale: 'en', strength: 2 })
            .lean();
        if (existing) {
            throw new ConflictException(`Designation "${trimmed}" already exists`);
        }

        const doc = await this.designationModel.create({ name: trimmed, isDefault: false });
        return doc.toObject();
    }
}
