const { empty } = require("../Helpers/Common");
const sequelize = require("../config/dbconnection");
const Sequelize = require('sequelize')

const Vehicle = sequelize.define('vehicles',{
    id:{ type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    name:{type:Sequelize.TEXT,allowNull:false},
    model:{type:Sequelize.TEXT,allowNull:false},
    type_of_vehicle:{type:Sequelize.CHAR(250),allowNull:true,defaultValue:null},
    vehicle_number:{type:Sequelize.TEXT,allowNull:false},
    assigned_driver:{type:Sequelize.INTEGER,allowNull:true,defaultValue:null},
    vehicle_image:{type:Sequelize.TEXT,allowNull:true,defaultValue:null},
    added_by: {type:Sequelize.TINYINT(200),allowNull:false},
    timestamp:{type:Sequelize.INTEGER,allowNull:false},
    status:{type:Sequelize.TINYINT,allowNull:false}
},{tableName:'vehicles',timestamps:false})

const AddVehicle=async(data)=>{
    const result = await Vehicle.create(data)
    return result
}

const updateVehicle=async(data,id)=>{
    
 let  result = await Vehicle.update(data,{
    where:{
        id:id
    },returning:true
 })

  if(result){
    return true
  }else{
    return false
  }
}

const getAllVehicles = async (content) => {
    try {
        
        let result = [];
        let contentCondition = '';

        if (content) {
            contentCondition = `AND v.name LIKE '%${content}%'`;
        }

        result = await sequelize.query(`
            SELECT v.*, dr.name AS driver_name, dr.profile_photo AS driver_photo
            FROM vehicles AS v
            LEFT JOIN driver AS dr ON v.assigned_driver = dr.id
            WHERE v.status = 1 ${contentCondition}
            ORDER BY v.id DESC
        `);

        if (result[0].length > 0) {
            return result[0];
        } else {
            return [];
        }
    } catch (error) {
        console.log(error);
    }
};

  
const getVehicleById=async(id)=>{
    try {
        let result = await sequelize.query(`select v.* from vehicles as v  where v.status = 1 and v.id = ${id}`)
        if(!empty(result)&& result[0].length===1){
          return  result[0]
        }else{
            return []
        }
    } catch (error) {
        console.log(error)
    }
 }
 const deleteVehicle=async(id)=>{
    const result = await Vehicle.destroy({
        where: {
          id,
        },
      })
    if(result){
        return true
    }else{
        return false
    }
 }
module.exports={
    AddVehicle,
    updateVehicle,
    getAllVehicles,
    getVehicleById,
    deleteVehicle,
}
