//
//  cntrlFuel.swift
//
//
//  Created by Michiel Carman on 4/5/2024.
//

import Fluent
import Vapor
import Crypto



struct cntrlFuel: RouteCollection {
    func boot(routes: RoutesBuilder) throws {
        let rts = routes.grouped("fuels")
        rts.get(use: index)
        rts.get(":x", use: read)
        rts.post(use: create)
        rts.delete(":x", use: delete)
        //Additional routs added here
    }
    
    func index(req: Request) async throws -> Response {
        guard let obj = try? await mdlFuel.ObjQuery(req: req).all() else {
            throw Abort(.badGateway, reason: "Something went wrong with this api.")
        }
        guard let response = try? await obj.encodeResponse(status: .ok, for: req) else{
            throw Abort(.noContent, reason: "Something went wrong decoding data.  Array could not be shown.")
        }
        return response
    }
    
    func read(req:Request) async throws -> Response{
        guard let obj = try? await mdlFuel.ObjQuery(req: req).first() else{
            throw Abort(.notFound, reason: "Fuel was not found.")
        }
        guard let response = try? await obj.encodeResponse(status: .ok, for: req) else {
            throw Abort(.noContent, reason: "Something went wrong decoding object.")
        }
        return response
    }
    
    func create(req: Request) async throws -> Response {
        
        guard let obj = try? req.content.decode(mdlFuel.self) else {
            throw Abort(.notAcceptable, reason: "Fuel json not formatted correctly or is missing parents.")
        }
        var exists = false
        if(obj.id != nil){
            obj._$idExists = true
            exists = true
        }
        guard let _ = try? await obj.save(on: req.db) else{
            throw Abort(.conflict, reason: "Something conflicts in the database. Fuel cannot be saved.")
        }
        
        guard let response = try? await obj.encodeResponse(status: exists ? .accepted : .created, for: req) else{
            throw Abort(.noContent, reason: "Something went wrong decoding data.  Fuel has been saved.")
        }
        return response
    }
    
    
    func delete(req: Request) async throws -> Response {
        guard let obj = try? await mdlFuel.ObjQuery(req: req).first() else {
            throw Abort(.notFound, reason: "Fuel's ID was not supplied.  Fuel will not be deleted")
        }
        guard let _ = try? await obj.delete(on: req.db) else{
            throw Abort(.conflict, reason: "There was a conflict deleting Fuel.  Make sure it has not children.")
        }
        guard let response = try? await obj.encodeResponse(status: .ok, for: req) else{
            throw Abort(.noContent, reason: "Something went wrong decoding data.  Fuel has been deleted.")
        }
        return response
    }
}

