import mongoose, { Schema, Document, models } from "mongoose";
import { Base } from "./base";

const BuildIbanSchema = new Schema({
    iban: { type: String, required: true },
    startDate: { type: Date, required: true },
    stopDate: { type: Date, required: true, default: new Date("2900-01-01T03:00:00+03:00") },
    bankCode: { type: String, required: true, default: "TR0000000000000" },
    xcomment: { type: String, required: true, default: "????" },
});

const BuildResponsibleSchema = new Schema({
    company: { type: Schema.Types.ObjectId, ref: "Company", required: true },
    person: { type: Schema.Types.ObjectId, ref: "Person", required: true },
});

const BuildInfoSchema = new Schema({
    govAddressCode: { type: String, required: true },
    buildName: { type: String, required: true },
    buildNo: { type: String, required: true },
    maxFloor: { type: Number, required: true },
    undergroundFloor: { type: Number, required: true },
    buildDate: { type: Date, required: true },
    decisionPeriodDate: { type: Date, required: true },
    taxNo: { type: String, required: true },
    liftCount: { type: Number, required: true },
    heatingSystem: { type: Boolean, required: true },
    coolingSystem: { type: Boolean, required: true },
    hotWaterSystem: { type: Boolean, required: true },
    blockServiceManCount: { type: Number, required: true },
    securityServiceManCount: { type: Number, required: true },
    garageCount: { type: Number, required: true },
    managementRoomId: { type: Number, required: true },
});

interface IBuildInterface extends Base, Document {
    buildType: Schema.Types.ObjectId;
    collectionToken: string;
    info: typeof BuildInfoSchema;
    site?: Schema.Types.ObjectId;
    address?: Schema.Types.ObjectId;
    ibans?: typeof BuildIbanSchema[];
    areas?: Schema.Types.ObjectId[];
    responsibles?: typeof BuildResponsibleSchema[];
}

const BuildSchema = new Schema<IBuildInterface>({
    buildType: { type: Schema.Types.ObjectId, ref: "BuildType", required: true },
    collectionToken: { type: String, required: true, unique: true },
    info: { type: BuildInfoSchema, required: true },
    site: { type: Schema.Types.ObjectId, ref: "Site", required: false },
    address: { type: Schema.Types.ObjectId, ref: "BuildAddress", required: false },
    areas: [{ type: Schema.Types.ObjectId, ref: "BuildArea", required: false }],
    ibans: [{ type: BuildIbanSchema, required: false }],
    responsibles: [{ type: BuildResponsibleSchema, required: false }],
}, { timestamps: true });

const Build = models.Build || mongoose.model<IBuildInterface>("Build", BuildSchema);

export { Build };
export type { IBuildInterface };
