import mongoose, { Schema, Document } from 'mongoose';

export interface IInspection extends Document {
    organizationId?: string;
    createdBy?: string; // Clerk User ID
    projectId: mongoose.Types.ObjectId;
    type: 'painting' | 'surface_treatment';

    // Common
    date?: Date | null;
    inspector?: string | null;
    appearance?: 'approved' | 'rejected' | 'notes' | null; // Unified status
    defects?: string | null; // Observations
    photos?: string[]; // URLs
    partTemperature?: number | null;
    weightKg?: number | null;

    // Painting Specific
    pieceDescription?: string | null;
    epsPoints?: (number | null)[];
    adhesionTest?: string | null;

    // Surface Treatment Specific
    batch?: string | null; // Lote
    treatmentExecutor?: string | null;
    treatmentType?: string | null; // Jateamento, Mecânica...
    cleaningDegree?: string | null; // Sa 2.5, St 3...
    roughnessReadings?: (number | null)[]; // 5 measurements
    flashRust?: string | null;
    temperature?: number | null;
    relativeHumidity?: number | null;
    period?: 'morning' | 'afternoon' | 'night' | null;
    applicationRecordId?: mongoose.Types.ObjectId; // Link to specific painting batch
    stockItemId?: mongoose.Types.ObjectId; // Link to Stock Item (Paint used)
    instrumentId?: mongoose.Types.ObjectId; // Link to Instrument used
}

const InspectionSchema: Schema = new Schema({
    organizationId: { type: String, index: true },
    createdBy: { type: String, index: true },
    projectId: { type: Schema.Types.ObjectId, ref: 'Project', required: true },
    applicationRecordId: { type: Schema.Types.ObjectId, ref: 'ApplicationRecord' },
    stockItemId: { type: Schema.Types.ObjectId, ref: 'StockItem' },
    instrumentId: { type: Schema.Types.ObjectId, ref: 'Instrument' },
    type: { type: String, enum: ['painting', 'surface_treatment'], default: 'painting', index: true },

    // Common
    date: { type: Date },
    inspector: { type: String },
    appearance: { type: String }, // approved, rejected, notes
    defects: { type: String },
    photos: [{ type: String }],
    partTemperature: { type: Number },
    weightKg: { type: Number },

    // Painting
    pieceDescription: { type: String },
    epsPoints: [{ type: Number }],
    adhesionTest: { type: String },

    // Surface Treatment
    batch: { type: String },
    treatmentExecutor: { type: String },
    treatmentType: { type: String },
    cleaningDegree: { type: String },
    roughnessReadings: [{ type: Number }],
    flashRust: { type: String },
    temperature: { type: Number },
    relativeHumidity: { type: Number },
    period: { type: String },
}, { timestamps: true });

export default mongoose.models.Inspection || mongoose.model<IInspection>('Inspection', InspectionSchema);
