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

export type TransportRouteDocument = TransportRoute & Document;

@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 TransportRoute extends BaseEntity {
    @Prop({ required: true, trim: true })
    name: string;

    @Prop({ trim: true })
    description?: string;

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

    @Prop({ required: true, min: 0 })
    monthlyFee: number;

    @Prop({ type: [String], default: [] })
    stops: string[];

    @Prop({ trim: true })
    vehicleNumber?: string;

    @Prop({ trim: true })
    driverName?: string;

    @Prop({ trim: true })
    driverPhone?: string;

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

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

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

export const TransportRouteSchema = SchemaFactory.createForClass(TransportRoute);
TransportRouteSchema.index({ academicYearId: 1 });
TransportRouteSchema.index({ name: 1, academicYearId: 1 }, { unique: true });
TransportRouteSchema.index({ isActive: 1 });
TransportRouteSchema.set('toJSON', { versionKey: false });
TransportRouteSchema.set('toObject', { versionKey: false });
