const jwt = require('jsonwebtoken')
const asyncHandler = require('./async')
const ErrorResponse = require("../utils/errorResponse")
const dotenv = require("dotenv")
const UserModel = require("../Model/User")
const StoreModel = require("../Model/StoreModel")
const { raw } = require('express')

//Require Dotenv
dotenv.config({
    path: "./Config/config.env",
})

// Protect route 
exports.protect = asyncHandler(async (req, res, next) => {
    let token
    if (req.headers.authorization && req.headers.authorization.startsWith("Bearer")) {
        token = req.headers.authorization.split(" ")[1];
    }
    if (!token) {
        next(new ErrorResponse("Invalid Token", 401))
    }

    try {
        console.log("TOKEN ", token)
        const decoded = jwt.verify(token, process.env.JWT_SECRET)
        console.log("decode : ", decoded)

        if (decoded.id == 1) {
            req.user = {
                "USER_ID": 1,
                "USER_CODE": "BCSA",
                "USER_NAME": "BCSA",
                "USER_DESC": "BC Admin",
                "FIRST_NAME": "Admin",
                "LAST_NAME": "BC",
                "ADDRESS": "",
                "PHONE": "012345678",
                "EMAIL": "",
                "MAP": "37.33233141,-122.0312186",
                "USER_STATUS": "1",
                "USER_TYPE": "S",
                "USER_LOG": "",
                "USER_CPAS": 0,
                "APPROVED": 1,
                "APPROVED_BY": "3248",
                "EMP_CODE": null,
                "USER_PERIOD": null,
                "FIELD_0": null,
                "FIELD_1": "SELLER",
                "FIELD_2": null,
                "FIELD_3": null,
                "FIELD_4": null,
                "FIELD_5": null,
                "FIELD_6": null,
                "FIELD_7": null,
                "FIELD_8": null,
                "FIELD_9": null,
                "USER_CREATED": "3248",
                "USER_CREDATE": "2024-03-18",
                "USER_UPDT": "3248",
                "DATE_UPDT": "2024-03-18",
            }
        }
        req.user = await UserModel.findOne({
            where: {
                USER_ID: decoded.id,
            },
            raw: true
        })
        if (!req.user) {
            return next(new ErrorResponse("User not found", 400));
        }

        if (req.user.USER_STATUS == 0) {
            return next(new ErrorResponse("User disabled", 400));
        }

        let store = await StoreModel.findOne({
            where: {
                DB_CODE: decoded.dbCode,
                DB_STAT: 'A'
            }
        })

        if (!store) {
            return next(new ErrorResponse("Store not found or disabled. Please try again", 400))
        }

        let preset = null
        let typeId = ""
        let saleType = ""
        let warehouse = ""
        console.log("USER ", req.user)
        req.user.DB_CODE = decoded.dbCode
        next()

    } catch (err) {
        console.log("ERROR ", err)
        return next(new ErrorResponse("Not authorized to access this route", 401))
    }
})

//Protect At Login
exports.protectAtlogin = asyncHandler(async (req, res, next) => {
    console.log("PROTECT AT LOGIN EXEC")
    let token;
    console.log("BEARER HEADER ", process.env.BEARER_HEADER)
    try {

        if (req.headers.authorization && req.headers.authorization.startsWith("Bearer")
        ) {
            token = req.headers.authorization.split(" ")[1];
        }
        if (token != process.env.BEARER_HEADER) {
            next(new ErrorResponse("Invalid Token", 400));
        } else {
            next();
        }
    } catch (error) {
        console.log("ERRROR ", error)
    }
})