//
//  mdlInspection.swift
//
//
//  Created by Michiel Carman on 2/16/24.
//


import Fluent
import Vapor
import Foundation
import FluentKit

final class mdlInspection: Model, Content {
    static let schema = "inspection"
    
    @ID(custom: "id", generatedBy: .database) var id: Int?
    
    @Parent(key: "workOrderSegmentId") var segment: mdlWorkOrderSegment
    @Parent(key: "inspectionLevelId") var level: mdlInspectionLevel
    @Field(key: "name") var name: String?
    @Field(key: "segment") var seg: String?
    @Field(key: "interval") var interval: String?
    
    @Children(for: \.$inspection) var categories: [mdlInspectionCategory]
    @Children(for: \.$inspection) var notes: [mdlNote]
    
    @Timestamp(key: "createDate", on: .create) var createdate: Date?
    @Field(key: "createUserId") var createuserid: Int?
    @Timestamp(key: "updateDate", on: .update) var updatedate: Date?
    @Field(key: "updateUserId") var updateuserid: Int?
    
    init() { }
    
    init(id: Int? = nil,
         name: String? = nil,
         interval: String? = nil,
         seg: String? = nil,
         segmentid: Int,
         levelid: Int,
         createuserid: Int? = nil,
         updateuserid: Int? = nil
    ) {
        self.id = id
        self.name = name
        self.interval = interval
        self.seg = seg
        self.$segment.$id.value = segmentid
        self.$level.$id.value = levelid
        self.createuserid = createuserid
        self.updateuserid = updateuserid
    }
}
extension mdlInspection{
    struct Create: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("inspection")
                .field("id", .int, .identifier(auto: true))
                .field("name", .string)
                .field("description", .string)
                .field("workOrderSegmentId", .int, .references("workOrderSegment", "id"))
                .field("inspectionLevelId", .int, .references("inspectionLevel", "id"))
                .field("createDate", .datetime)
                .field("createUserId", .int)
                .field("updateDate", .datetime)
                .field("updateUserId", .int)
                .create()
        }
        
        func revert(on database: Database) async throws {
            try await database.schema("inspection").delete()
        }
    }
    struct Mod1: AsyncMigration{
        func prepare(on database: Database) async throws {
            try await database.schema("inspection")
                .deleteField("description")
                .field("segment", .string)
                .field("interval", .string)
                .update()
        }
        func revert(on database: Database) async throws {
            try await database.schema("inspection")
                .deleteField("segment")
                .deleteField("interval")
                .field("description", .string)
                .update()
        }
    }
    public static func ObjQuery(req: Request) async throws -> QueryBuilder<mdlInspection>{
        
        let query = mdlInspection.query(on: req.db)
            .with(\.$segment)
            .with(\.$categories)
            .with(\.$level)
            .with(\.$notes)
        
        if let x = req.parameters.get("x"){
            let decryptedString = try CustomCrypto.DecryptString(input: x)
            let array =  decryptedString.components(separatedBy: ":")
            ///This call is the standard get by id call
            if (array.count == 1){
                let id = Int(array[0])!
                return query.filter(\.$id == id)
            }
            ///Optional else if if there are multiple parameters in the call
            ///You must include an else for each call that has parameters
            ///Need to check the endpoint to get the right filter statements
            ///else if(x.count == 2){
            ///    let username = x[0]
            ///    let password = x[1]
            ///    return query.filter(\.$username == username).filter(\.$password == password)
            ///}
            else{
                throw Abort(.badRequest)
            }
            
        }
        else{
            return query
        }
    }
}

