const config = require('config.json');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = require('helpers/db');
const { Op, QueryTypes } = require('sequelize');

module.exports = {
    getAll,
    getFilter,
    getOne, 
    getName,
    getOption,
    getCount,
    create,
    update,
    delete: _delete
};

// ============================= || FUNCTION || ============================= //

async function getAll() {
    const customerLists = await db.ASA_CustomerList.findAll({
        order: [
            ['modified', 'DESC']
        ],
    });

    const success = true;
    const message = "Loaded Successfully!";

    return  { customerLists: customerLists, success, message };
}

async function getFilter(params) {
    const filterConditions = {};
    
    if (params.customer_name) {
        filterConditions.customer_name = {
            [Op.like]: `%${params.customer_name}%`,
        };
    }

    if (params.company) {
        filterConditions.company = {
            [Op.like]: `%${params.company}%`,
        };
    }

    const customerLists = await db.ASA_CustomerList.findAll({
        where: filterConditions,
        order: [
            ['modified', 'DESC']
        ],
        
    });

    const success = true;
    const message = "Loaded Successfully!";

    return  { customerLists: customerLists, success, message };
}

async function getOne(id) {
    const customerList = await getCustomerList(id); 

    const success = true;
    const message = "Loaded Successfully!";

    return  { customerList: customerList, success, message };
}

async function getName(id) {
    const customerList = await db.ASA_CustomerList.findAll({
        attributes: ['customer_name'],
        where: { 
            id: id 
        },
    });

    const success = true;
    const message = "Loaded Successfully!";

    return  { customerList: customerList, success, message };
}

async function getOption() {
    const customerLists = await db.ASA_CustomerList.findAll({
        attributes: ['id', 'customer_name', 'customer_type', 'market_segment', 'pic', 'ho_address', 'plant_address','industry','am_ae', 'territory'],
        where: { 
            enabled: true 
        },
    });

    const success = true;
    const message = "Loaded Successfully!";

    return  { customerLists: customerLists, success, message };
}

async function getCount() {
    var customerListCount = await db.ASA_CustomerList.count({ 
        where: { 
            enabled: true 
        } 
    })

    const success = true;
    const message = "Loaded Successfully!";

    // return
    return { count: customerListCount, success, message};
}

async function create(params) {
    // validate
    if (await db.ASA_CustomerList.findOne({ where: { customer_name: params.customer_name } })) {
        throw 'Customer name "' + params.customer_name + '" is already taken';
    }

    // default params
    if (!params.enabled) {
        params.enabled = true;
    }

    // save
    await db.ASA_CustomerList.create(params);

    // default format return
    // const customerLists = await db.ASA_CustomerList.findAll({
    //     order: [
    //         ['modified', 'DESC']
    //     ],
    // });
    
    const success = true;
    const message = "Your data has been saved!";

    // return
    return  { success, message }
}

async function update(id, params) {
    const customerList = await getCustomerList(id);

    // validate
    const customerListChanged = params.customer_name && customerList.customer_name !== params.customer_name;
    if (customerListChanged && await db.ASA_CustomerList.findOne({ where: { customer_name: params.customer_name } })) {
        throw ' "' + params.customer_name + '" is already taken. Try again!';
    }
    // copy params to user and save
    Object.assign(customerList, params);
    await customerList.save();

    // default format return
    // const customerLists = await db.ASA_CustomerList.findAll({
    //     order: [
    //         ['modified', 'DESC']
    //     ],
    // });

    const success = true;
    const message = "Your data has been saved!";

    // return
    return  { success, message }
}

async function _delete(id) {
    const customerList = await getCustomerList(id);
    await customerList.destroy();

    // const customerLists = await db.ASA_CustomerList.findAll({
    //     order: [
    //         ['modified', 'DESC']
    //     ],
    // });

    const success = true;
    const message = "Your data has been deleted!";

    return  { success, message }
}

// ============================= || HELPER FUNCTION || ============================= //

async function getCustomerList(id) {
    const customerList = await db.ASA_CustomerList.findByPk(id);
    if (!customerList) throw 'Customerer List not found, please kindly check!';
    return customerList;
}
