package dao

import (
	"fmt"
	"intent-system/pkg/dal/models"

	"github.com/civet148/log"
	"github.com/civet148/sqlca/v2"
)

const (
	LoginType_Admin1    = 0
	LoginType_Customer1 = 1
)

type DeployDAO struct {
	db *sqlca.Engine
}

func NewDeployDAO(db *sqlca.Engine) *DeployDAO {

	return &DeployDAO{
		db: db,
	}
}

func (dao *DeployDAO) Insert(dos ...*models.DeployDO) (lastId int64, err error) {
	if lastId, err = dao.db.Model(&dos).Table(models.TableNameDeploy).Insert(); err != nil {
		log.Errorf(err.Error())
		return
	}
	return
}

func (dao *DeployDAO) UpdateByNid(do *models.DeployDO, columns ...string) (err error) {
	if _, err = dao.db.Model(do).
		Table(models.TableNameDeploy).
		Select(columns...).
		Eq(models.DEPLOY_COLUMN_NID, do.Nid).
		Update(); err != nil {
		log.Errorf(err.Error())
		return
	}
	return
}

func (dao *DeployDAO) UpdateStatusByAppID(appID int64, newStatus string) error {
	var record models.DeployDO
	_, err := dao.db.Model(&record).
		Table(models.TableNameDeploy).
		Where("n_id = ?", appID).
		Limit(1).
		Query()
	if err != nil {
		log.Errorf("根据 appID 查询 DeployDO 失败: %v", err)
		return err
	}
	if record.Id == 0 {
		log.Warnf("找不到 appID=%d 对应的部署记录", appID)
		return fmt.Errorf("无部署记录")
	}

	// 🔧 修正拼接，避免语法错误
	updateObj := &models.DeployDO{
		Status: newStatus,
	}
	_, err = dao.db.Model(updateObj).
		Table(models.TableNameDeploy).
		Select(models.DEPLOY_COLUMN_STATUS).
		Where("mb_uuid = ? AND repo_name = ? AND user_name = ?", record.MbUuid, record.RepoName, record.UserName).
		Update()
	if err != nil {
		log.Errorf("批量更新状态失败: %v", err)
		return err
	}
	return nil
}

// SelectDeployById
func (dao *DeployDAO) SelectDeployById(id int64, columns ...string) (do *models.DeployDO, err error) {
	log.Infof(".......dal_dao.................Deploy.......................\n\n")
	if _, err = dao.db.Model(&do).Table(models.TableNameDeploy).Id(id).Select(columns...).Query(); err != nil {
		return nil, log.Errorf(err.Error())
	}
	return
}

// query records by n_id
func (dao *DeployDAO) QueryByNid(id int64, columns ...string) (do *models.DeployDO, err error) {
	if _, err = dao.db.Model(&do).Table(models.TableNameDeploy).Where("n_id = ?", id).Select(columns...).Query(); err != nil {
		return nil, log.Errorf(err.Error())
	}
	return
}

func (dao *DeployDAO) DeleteByNid(nid int64) error {
	_, err := dao.db.Where("n_id = ?", nid).Table(models.TableNameDeploy).Delete()
	return err
}

func (dao *DeployDAO) DeleteByFields(mbUuid, repoName, userName string) error {
	_, err := dao.db.
		Table(models.TableNameDeploy).
		Where("mb_uuid = ? AND repo_name = ? AND user_name = ?", mbUuid, repoName, userName).
		Delete()
	return err
}

func (dao *DeployDAO) UpdateStatusByFields(mbUuid, repoName, userName string, strStatus string) error {
	updates := map[string]interface{}{
		"status": strStatus,
	}
	_, err := dao.db.
		Model(&updates).
		Table(models.TableNameDeploy).
		And("mb_uuid = ?", mbUuid).
		And("repo_name = ?", repoName).
		And("user_name = ?", userName).
		Update()
	return err
}

func (dao *DeployDAO) DeleteByUserRepoUUIDAndStatus(user, repo, uuid, status string) error {
	log.Infof("🔥 Start to delete record from 'deploy' table")
	log.Infof("🧩 Conditions: user_name=%s, repo_name=%s, mb_uuid=%s, status=%s", user, repo, uuid, status)

	affected, err := dao.db.Table(models.TableNameDeploy).
		Where("user_name = ? AND repo_name = ? AND mb_uuid = ? AND status = ?", user, repo, uuid, status).
		Delete()
	if err != nil {
		log.Errorf("❌ Delete failed: %v", err)
		return err
	}

	log.Infof("✅ Successfully deleted %d record(s) with user_name=%s, repo_name=%s, mb_uuid=%s, status=%s",
		affected, user, repo, uuid, status)
	return nil
}

func (dao *DeployDAO) CountByUserRepoUUIDAndStatus(user, repo, uuid, status string) (int64, error) {
	var count int64
	_, err := dao.db.Model(&count).
		Table(models.TableNameDeploy).
		Where("user_name = ? AND repo_name = ? AND mb_uuid = ? AND status = ?", user, repo, uuid, status).
		Count("id").
		Query()
	if err != nil {
		log.Errorf("❌ Count failed: %v", err)
		return 0, err
	}

	log.Infof("✅ Counted %d record(s) with user_name=%s, repo_name=%s, mb_uuid=%s, status=%s",
		count, user, repo, uuid, status)
	return count, nil
}
