package dev_services

import (
	"cpone/db"
	"cpone/models"
	dbx "cpone/package/database"
	"fmt"
	"math"
	"strconv"
	"strings"

	"go.uber.org/zap"
)

func NewMdUserGroupServices(uStore db.AppStore) *MdUserGroupServices {

	return &MdUserGroupServices{

		MdUserGroupStore: uStore,
	}
}

type MdUserGroupServices struct {
	MdUserGroupStore db.AppStore
}

func (su *MdUserGroupServices) GetListMdUserGroup(search string, currentPage int, rowPerPage int) ([]models.UserGroupV1, int, error) {
	var userGroupList []models.UserGroupV1
	var totalData int
	offset := (currentPage - 1) * rowPerPage
	prm := "%" + strings.TrimSpace(search) + "%"
	querytotal := `
		SELECT COUNT(*) 
		FROM m_usergroup
		WHERE M_UserGroupIsActive = 'Y'
		AND (M_UserGroupCode LIKE ? OR M_UserGroupName LIKE ?) 
	`
	if err := dbx.Handlex.Get(&totalData, querytotal, prm, prm); err != nil {
		return nil, 0, fmt.Errorf("error querying database: %v", err)
	}
	query := `
		SELECT
			ROW_NUMBER() OVER () AS nomor,
			M_UserGroupID,
			M_UserGroupCode,
			M_UserGroupName,
			M_UserGroupCreated,
			M_UserGroupLastUpdated,
			M_UserGroupIsActive
		FROM m_usergroup
		WHERE M_UserGroupIsActive = 'Y'
		AND (M_UserGroupCode LIKE ? OR M_UserGroupName LIKE ?)
		order by M_UserGroupID ASC
		LIMIT ? OFFSET ?
	`

	if err := dbx.Handlex.Select(&userGroupList, query, prm, prm, rowPerPage, offset); err != nil {
		return nil, 0, fmt.Errorf("error querying database: %v", err)
	}
	totalPage := int(math.Ceil(float64(totalData) / float64(rowPerPage)))

	return userGroupList, totalPage, nil
}
func (ug *MdUserGroupServices) GetMdUserGroupByID(id string) (models.UserGroupV1, error) {
	logger, _ := zap.NewProduction()

	var data models.UserGroupV1
	err := dbx.Handlex.Get(&data, `SELECT * FROM m_usergroup
	WHERE M_UserGroupID = ?`, id)

	if err != nil {
		defer logger.Sync()
		logger.Error("Error get data ug by id vs",
			zap.String("ID", id),
			zap.Error(err),
		)
		return data, fmt.Errorf("QUERY_FAILED")
	}
	return data, nil
}

func (ug *MdUserGroupServices) AddMdUserGroup(code string, name string) (models.UserGroupV1, error) {
	logger, _ := zap.NewProduction()
	var data models.UserGroupV1
	var datacek []models.UserGroupV1

	qryCek := `SELECT M_UserGroupCode FROM m_usergroup WHERE M_UserGroupCode = ? AND M_UserGroupIsActive = 'Y'`
	err := dbx.Handlex.Select(&datacek, qryCek, code)

	if err != nil {
		defer logger.Sync()
		logger.Error("Error cek data by code",
			zap.String("code", code),
			zap.Any("datacek", datacek),
		)
		return data, fmt.Errorf("QUERY_FAILED")
	}
	if len(datacek) > 0 {
		defer logger.Sync()
		logger.Error("Code already taken by another data",
			zap.String("code", code),
		)
		return data, fmt.Errorf("code sudah dipakai")
	}
	qry := `INSERT INTO m_usergroup
			(M_UserGroupCode,
			M_UserGroupName)
			VALUES (?,?);`
	// time.Sleep(5 * time.Second)
	rst := dbx.Handlex.MustExec(qry, code, name)
	insertedID, err := rst.LastInsertId()
	if err != nil {
		defer logger.Sync()
		logger.Error("Error Insert usergroup",
			zap.String("code", code),
			zap.String("name", name),
		)
		return data, fmt.Errorf("QUERY_FAILED")
	}
	s := strconv.Itoa(int(insertedID))
	data, err = ug.GetMdUserGroupByID(s)
	if err != nil {
		defer logger.Sync()
		logger.Error("Error get usergroup by id",
			zap.String("code", code),
			zap.String("name", name),
		)
		return data, fmt.Errorf("QUERY_FAILED")
	}
	return data, nil
}
func (ug *MdUserGroupServices) EditMdUsergroup(id string, code string, name string) (models.UserGroupV1, error) {
	logger, _ := zap.NewProduction()
	var data models.UserGroupV1
	var datacek []models.UserGroupV1

	qryCek := `SELECT M_UserGroupCode FROM m_usergroup WHERE M_UserGroupCode = ? AND M_UserGroupIsActive = 'Y' AND M_UserGroupID <> ?`
	err := dbx.Handlex.Select(&datacek, qryCek, code, id)

	if err != nil {
		defer logger.Sync()
		logger.Error("Error cek data by code",
			zap.String("code", code),
			zap.Any("datacek", datacek),
		)
		return data, fmt.Errorf("QUERY_FAILED")
	}
	if len(datacek) > 0 {
		defer logger.Sync()
		logger.Error("Code already taken by another data",
			zap.String("code", code),
		)
		return data, fmt.Errorf("code sudah dipakai")
	}
	qry := `UPDATE m_usergroup
			SET M_UserGroupCode = ?,
			M_UserGroupName= ?
			WHERE M_UserGroupID = ?;`
	// time.Sleep(5 * time.Second)
	rst := dbx.Handlex.MustExec(qry, code, name, id)
	_, err = rst.RowsAffected()
	if err != nil {
		defer logger.Sync()
		logger.Error("Error Update usergroup",
			zap.String("code", code),
			zap.String("name", name),
		)
		return data, fmt.Errorf("QUERY_FAILED")
	}

	data, err = ug.GetMdUserGroupByID(id)
	if err != nil {
		defer logger.Sync()
		logger.Error("Error get usergroup by id",
			zap.String("code", code),
			zap.String("name", name),
		)
		return data, fmt.Errorf("QUERY_FAILED")
	}
	return data, nil
}

func (ug *MdUserGroupServices) DeleteMdUserGroup(id string) (models.UserGroupV1, error) {
	logger, _ := zap.NewProduction()
	var data models.UserGroupV1
	qry := `UPDATE m_usergroup
			SET M_UserGroupIsActive = 'N',
			M_UserGroupDeleted = NOW(),
			M_UserGroupDeletedUserID = '1'
			WHERE M_UserGroupID = ?;`
	// time.Sleep(5 * time.Second)
	rst := dbx.Handlex.MustExec(qry, id)
	_, err := rst.RowsAffected()
	if err != nil {
		defer logger.Sync()
		logger.Error("Error delete usergroup",
			zap.String("id", id),
		)
		return data, fmt.Errorf("QUERY_FAILED")
	}

	data, err = ug.GetMdUserGroupByID(id)
	if err != nil {
		defer logger.Sync()
		logger.Error("Error get usergroup by id",
			zap.String("id", id),
		)
		return data, fmt.Errorf("QUERY_FAILED")
	}
	return data, nil
}
func (su *MdUserGroupServices) GetMdUserGroupBreadCrumb(title string) (models.BreadCrumbV1, error) {
	var ret models.BreadCrumbV1

	dummyBreadcrumb := []models.BreadCrumbV1{
		{
			Title: "Master User Group",
			Item: []models.ItemBreadCrumbV1{
				{
					Item: "Dashboard",
					Url:  "/dev/dashboard",
				},
				{
					Item: "Master",
					Url:  "/dev/master",
				},
				{
					Item: "User Group",
					Url:  "",
				},
			},
		},

		{
			Title: "Master User",
			Item: []models.ItemBreadCrumbV1{
				{
					Item: "Dashboard",
					Url:  "/dev/dashboard",
				},
				{
					Item: "Master",
					Url:  "/dev/master",
				},
				{
					Item: "User",
					Url:  "",
				},
			},
		},
	}

	for _, breadcrumb := range dummyBreadcrumb {
		if breadcrumb.Title == title {
			ret = breadcrumb
			return ret, nil
		}
	}

	return ret, nil
}
