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

import Fluent
import Vapor
import Foundation
import FluentKit

final class mdlOilSample: Model, Content {
    static let schema = "oilSample"
    
    @ID(custom: "id", generatedBy: .database) var id: Int?
    
    @Parent(key: "workOrderSegmentId") var segment: mdlWorkOrderSegment
    
    @Field(key: "name") var name: String?
    @Field(key: "code") var code: String?
    @Field(key: "l1Name") var l1name: String?
    @Field(key: "l1Code") var l1code: String?
    @Field(key: "l2Name") var l2name: String?
    @Field(key: "l2Code") var l2code: String?
    @Field(key: "meterReading") var meterreading: Decimal?
    @Field(key: "previousMeterReading") var previousmeterreading: Decimal?
    @Field(key: "hoursOnOil") var hoursonoil: Decimal?
    @Field(key: "oilAdded") var oiladded: Decimal?
    @Field(key: "unit") var unit: String?
    @Field(key: "jobSite") var jobsite: String?
    @Field(key: "fluid") var fluid: String?
    @Field(key: "viscosity") var viscosity: String?
    @Field(key: "oilChanged") var oilchanged: Bool?
    @Field(key: "filterChanged") var filterchanged: Bool?
    @Field(key: "level") var level: String?
    @Field(key: "comment") var comment: String?
    @Field(key: "sortOrder") var sortorder: Int?
    
    @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, segmentid: Int, name: String? = nil, code: String? = nil, l1name: String? = nil, l1code: String? = nil, l2name: String? = nil, l2code: String? = nil, meterreading: Decimal? = nil, previousmeterreading: Decimal? = nil, hoursonoil: Decimal? = nil, oiladded: Decimal? = nil, unit: String? = nil, jobsite: String? = nil, fluid: String? = nil, viscosity: String? = nil, oilchanged: Bool? = nil, filterchanged: Bool? = nil, level: String? = nil, comment: String? = nil, sortorder: Int? = nil, createuserid: Int? = nil, updateuserid: Int? = nil) {
        self.id = id
        self.$segment.$id.value = segmentid
        self.name = name
        self.code = code
        self.l1name = l1name
        self.l1code = l1code
        self.l2name = l2name
        self.l2code = l2code
        self.meterreading = meterreading
        self.previousmeterreading = previousmeterreading
        self.hoursonoil = hoursonoil
        self.oiladded = oiladded
        self.unit = unit
        self.jobsite = jobsite
        self.fluid = fluid
        self.viscosity = viscosity
        self.oilchanged = oilchanged
        self.filterchanged = filterchanged
        self.level = level
        self.comment = comment
        self.sortorder = sortorder
        self.createuserid = createuserid
        self.updateuserid = updateuserid
    }
}

extension mdlOilSample{
    struct Create: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("oilSample")
                .field("id", .int, .identifier(auto: true))
                .field("segmentId", .int, .references("segment", "id"))
                .field("name", .string)
                .field("code", .string)
                .field("l1Name", .string)
                .field("l1Code", .string)
                .field("l2Name", .string)
                .field("l2Code", .string)
                .field("meterReading", .float)
                .field("previousMeterReading", .float)
                .field("hoursOnOil", .float)
                .field("oilAdded", .float)
                .field("unit", .string)
                .field("jobSite", .string)
                .field("fluid", .string)
                .field("viscosity", .string)
                .field("oilChanged", .bool)
                .field("filterChanged", .bool)
                .field("level", .string)
                .field("comment", .string)
                .field("createDate", .datetime)
                .field("createUserId", .int)
                .field("updateDate", .datetime)
                .field("updateUserId", .int)
                .create()
        }

        func revert(on database: Database) async throws {
            try await database.schema("oilSample").delete()
        }
    }
    struct Mod1: AsyncMigration{
        func prepare(on database: Database) async throws {
            try await database.schema("oilSample")
                .field("sortOrder", .int)
                .update()
                
        }

        func revert(on database: Database) async throws {
            try await database.schema("oilSample")
                .deleteField("sortOrder")
                .update()
        }
    }
    struct Mod2: AsyncMigration{
        func prepare(on database: Database) async throws {
            try await database.schema("oilSample")
                .deleteField("segmentId")
                .field("workOrderSegmentId", .int, .references("workOrderSegment", "id"))
                .update()
                
        }

        func revert(on database: Database) async throws {
            try await database.schema("oilSample")
                .deleteField("workOrderSegmentId")
                .field("segmentId", .int, .references("segment", "id"))
                .update()
        }
    }
    public static func ObjQuery(req: Request) async throws -> QueryBuilder<mdlOilSample>{
        
        let query = mdlOilSample.query(on: req.db)
            .with(\.$segment)
        
        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
        }
    }
}
