//
//  cntrlUser.swift
//
//
//  Created by Michiel Carman on 4/1/24.
//

import Fluent
import Vapor
import Crypto



struct cntrlUser: RouteCollection {
    func boot(routes: RoutesBuilder) throws {
        let rts = routes.grouped("users")
        rts.get(use: index)
        rts.get("login", ":x", use: login)
        rts.get(":x", use: read)
        rts.post(use: create)
        rts.delete(":x", use: delete)
    }
    
    func login(req: Request) async throws -> Response{
        guard let obj = try? await mdlUser.ObjQuery(req: req).first() else {
            throw Abort(.unauthorized, reason: "Username or Password or Both are invalid.")
        }
        guard let response = try? await obj.encodeResponse(status: .ok, for: req) else {
            throw Abort(.noContent, reason: "Something went wrong decoding data.  User has been authenticated.")
        }
        return response
    }

    func index(req: Request) async throws -> Response {
        guard let obj = try? await mdlUser.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 mdlUser.ObjQuery(req: req).first() else{
            throw Abort(.notFound, reason: "User 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(mdlUser.self) else {
            throw Abort(.notAcceptable, reason: "User 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. User 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.  User has been saved.")
        }
        return response
    }
    

    func delete(req: Request) async throws -> Response {
        guard let obj = try? await mdlUser.ObjQuery(req: req).first() else {
            throw Abort(.notFound, reason: "User's ID was not supplied.  User will not be deleted")
        }
        guard let _ = try? await obj.delete(on: req.db) else{
            throw Abort(.conflict, reason: "There was a conflict deleting User.  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.  User has been deleted.")
        }
        return response
    }
    
    func createToken(req: Request) async throws -> Response{
        guard let obj = try? await mdlUser.ObjQuery(req: req).field(\.$id).field(\.$username).first() else{
            throw Abort(.notFound, reason: "User was not found.")
        }
        guard let exp = try? await mdlLicense.query(on: req.db).first() else {
            throw Abort(.notFound)
        }
        let token = Token(userid: obj.id!, token: [UInt8].random(count: 16).base64, source: .signup, expiresat: exp.expires)
        try await token.save(on: req.db)
        guard let response = try? await token.encodeResponse(status: .ok, for: req) else{
            throw Abort(.noContent, reason: "Something went wrong decoding data.  Token has been deleted.")
        }
        return response
    }
}
