const response = require('../../../helpers/responses')
const db = require('../../../../models/migration')
const errorHandler = require('../../../middlewares/errorHandler')
const {sequelize} = require('../../../../models/migration')
const { where } = require('sequelize')
const Branch = db.Branch

const getAll = async (req, res) => {
    try {
    const branch = await Branch.findAll({
            order: [['created_at', 'DESC']]
        })
        return response.success(res, branch, 'successfully loaded')
    } catch (error) {
        errorHandler(error, req, res)
        return response.failed(res, 500, error.message)
    }
}

const create = async (req, res) => {
    const t = await sequelize.transaction()
    try {
        const user_id = req.user.id
        const body = req.body

        const branch = await Branch.create({
            ...body,
            user_id
        })

        await t.commit()
        return response.success(res, branch, 'create successfuly')
    } catch (error) {
        errorHandler(error, req, res)
        return response.failed(res, 500, error.message)
    }
}

const update = async (req, res) => {
    const t = await sequelize.transaction()
    try {
        const id = req.params.id
        const body = req.body
        const user_id = req.user.id

        const branch = await Branch.findOne({
            where: {id},
            transaction: t
        })

        if (!branch) {
            await t.rollback()
            return response.failed(res, 404, 'Data Not Found')
        }

        const branchUpdate = await branch.update({
            ...body,
            user_id
        })

        await t.commit()
        return response.success(res, branchUpdate, 'Updated Successfuly')
    

    } catch (error) {
        await t.rollback()
        errorHandler(error, req, res)
        return response.failed(res, 500, error.message)
    }
}

const destroy = async (req, res) => {
    try {
        const id = req.params.id
        const branch = await Branch.findOne({
            where: { id },
        })

        if (!branch) {
            return response.failed(res, 404, 'Data Not Found')
        }
        await branch.destroy();
        return response.success(res, null, 'Deleted Successfuly')

    } catch (error) {
        errorHandler(error, req, res)
        return response.failed(res, 500, error.message)
    }
}

module.exports = {
    getAll,
    create,
    update,
    destroy
}