import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { BaseEntity } from '../../common/entities/base.entity';

export type FeeStructureDocument = FeeStructure & Document;

@Schema({ _id: false })
export class SubFee {
    @Prop({ required: true, trim: true }) name: string;
    @Prop({ required: true, min: 0 }) amount: number;
}
export const SubFeeSchema = SchemaFactory.createForClass(SubFee);

@Schema({ _id: false })
class LateFineSlab {
    @Prop({ required: true, min: 1 }) startDay: number;
    @Prop({ required: true, min: 1 }) endDay: number;
    @Prop({ required: true, min: 0 }) amount: number;
}
const LateFineSlabSchema = SchemaFactory.createForClass(LateFineSlab);

@Schema({ _id: false })
class LateFineRule {
    @Prop({ default: false }) enabled: boolean;
    @Prop({ enum: ['percentage', 'per_day', 'day_wise_slab'], default: 'per_day' })
    type: 'percentage' | 'per_day' | 'day_wise_slab';
    @Prop({ default: 0, min: 0 }) amountPerDay: number;
    @Prop({ default: 0, min: 0 }) percentage: number;
    @Prop({ type: [LateFineSlabSchema], default: [] }) slabs: LateFineSlab[];
}
const LateFineRuleSchema = SchemaFactory.createForClass(LateFineRule);

@Schema({ timestamps: true })
export class FeeStructure extends BaseEntity {
    @Prop({ required: true, trim: true })
    name: string;

    @Prop({ required: true, enum: ['one-time', 'monthly', 'quarterly', 'yearly'], default: 'one-time' })
    feeType: 'one-time' | 'monthly' | 'quarterly' | 'yearly';

    @Prop({ required: true })
    academicYearId: string;

    @Prop({ required: true, min: 1 })
    amount: number;

    @Prop({ type: [String], required: true })
    classIds: string[];

    @Prop({ min: 1, max: 12, default: 1 })
    dueMonth: number;

    @Prop({ required: true, min: 1, max: 31 })
    dueDay: number;

    @Prop({ required: false })
    startDate?: Date;

    @Prop({ required: false })
    endDate?: Date;

    @Prop({ default: false })
    enableSubFees: boolean;

    @Prop({ type: [SubFeeSchema], default: [] })
    subFees: SubFee[];

    @Prop({ type: LateFineRuleSchema, default: () => ({ enabled: false, type: 'per_day', amountPerDay: 0, percentage: 0, slabs: [] }) })
    lateFine: LateFineRule;

    @Prop({ default: true })
    isActive: boolean;
}

export const FeeStructureSchema = SchemaFactory.createForClass(FeeStructure);
FeeStructureSchema.index({ academicYearId: 1, classIds: 1 });
FeeStructureSchema.index({ isActive: 1 });
FeeStructureSchema.set('toJSON', { versionKey: false });
FeeStructureSchema.set('toObject', { versionKey: false });
