//
//  mdlWorkOrder.swift
//
//
//  Created by Michiel Carman on 1/24/24.
//

import Fluent
import Vapor
import Foundation
import FluentKit

final class mdlWorkOrder: Model, Content {
    static let schema = "workOrder"
    
    @ID(custom: "id", generatedBy: .database) var id: Int?
    
    @Field(key: "number") var number: String?
    @Field(key: "meterReading") var meterreading: Decimal?
    @Field(key: "specialInstructions") var specialinstructions: String?
    @Field(key: "scheduledStartDate") var scheduledstartdate: Date?
    @Field(key: "scheduledEndDate") var scheduledenddate: Date?
    @Field(key: "startDate") var startdate: Date?
    @Field(key: "endDate") var enddate: Date?
    @Field(key: "approvedDate") var approveddate: Date?
    
    @OptionalParent(key: "customerId") var customer: mdlCustomer?
    @OptionalParent(key: "equipmentId") var equipment: mdlEquipment?
    @OptionalParent(key: "statusId") var status: mdlStatus?
    @OptionalParent(key: "priorityId") var priority: mdlPriority?
    @OptionalParent(key: "technicianUserId") var technician: mdlUser?
    @OptionalParent(key: "reasonId") var reason: mdlReason?
    @OptionalParent(key: "incompleteReasonId") var incompletereason: mdlIncompleteReason?
    @OptionalParent(key: "fuelId") var fuel: mdlFuel?
    @OptionalParent(key: "workOrderFlowId") var workorderflow: mdlWorkOrderFlow?
    
    @Siblings(through: mdlWorkOrderAttachment.self, from: \.$workorder, to: \.$equipment) var attachments: [mdlEquipment]
    
    @Children(for: \.$workorder) var signatures: [mdlSignature]
    @Children(for: \.$workorder) 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
         , number: String? = nil
         , meterreading: Decimal? = nil
         , specialinstructions: String? = nil
         , scheduledstartdate: Date? = nil
         , scheduledenddate: Date? = nil
         , startdate: Date? = nil
         , enddate: Date? = nil
         , approveddate: Date? = nil
         , customerid: Int? = nil
         , equipmentid: Int? = nil
         , statusid: Int? = nil
         , priorityid: Int? = nil
         , technicianuserid: Int? = nil
         , reasonid: Int? = nil
         , incompletereasonid: Int? = nil
         , fuelid: Int? = nil
         , workorderflowid: Int? = nil
         , createuserid: Int? = nil
         , updateuserid: Int? = nil
    ) {
        self.id = id
        self.number = number
        self.meterreading = meterreading
        self.specialinstructions = specialinstructions
        self.scheduledenddate = scheduledstartdate
        self.scheduledenddate = scheduledenddate
        self.startdate = startdate
        self.enddate = enddate
        self.approveddate = approveddate
        self.$customer.$id.value = customerid!
        self.$equipment.$id.value = equipmentid!
        self.$status.$id.value = statusid!
        self.$priority.$id.value = priorityid!
        self.$technician.$id.value = technicianuserid!
        self.$reason.$id.value = reasonid!
        self.$incompletereason.$id.value = incompletereasonid!
        self.$fuel.$id.value = fuelid!
        self.$workorderflow.$id.value = workorderflowid!
        self.createuserid = createuserid ?? -1
        self.updateuserid = updateuserid ?? -1
    }
}

extension mdlWorkOrder{
    struct Create: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("workOrder")
                .field("id", .int, .identifier(auto: true))
                .field("number", .string)
                .field("meterReading", .float)
                .field("specialInstructions", .string)
                .field("scheduledStartDate", .datetime)
                .field("scheduledEndDate", .datetime)
                .field("startDate", .datetime)
                .field("endDate", .datetime)
                .field("approvedDate", .datetime)
                .field("customerId", .int)
                .field("equipmentId", .int)
                .field("statusId", .int)
                .field("priorityId", .int)
                .field("technicianUserId", .int)
                .field("reasonId", .int)
                .field("incompleteReasonId", .int)
                .field("fuelId", .int)
                .field("createDate", .datetime)
                .field("createUserId", .int)
                .field("updateDate", .datetime)
                .field("updateUserId", .int)
                .create()
        }

        func revert(on database: Database) async throws {
            try await database.schema("workOrder").delete()
        }
    }
    struct Mod1: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("workOrder")
                .field("workOrderFlowId", .int, .references("workOrderFlow", "id"))
                .update()
        }

        func revert(on database: Database) async throws {
            try await database.schema("workOrder")
                .deleteField("workOrderFlowId")
                .update()
        }
    }
    public static func ObjQuery(req: Request) async throws -> QueryBuilder<mdlWorkOrder>{
        
        let query = mdlWorkOrder.query(on: req.db)
            .with(\.$customer)
            .with(\.$equipment)
            .with(\.$status)
            .with(\.$priority)
            .with(\.$technician)
            .with(\.$reason)
            .with(\.$incompletereason)
            .with(\.$fuel)
            .with(\.$workorderflow)
            .with(\.$attachments)
            .with(\.$signatures)
            .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
        }
    }
}



