package creditlimit

import (
	"system-altrak/internal/domain"
	"system-altrak/internal/repository"
)

type CreditLimitRepository interface {
	Create(cl *domain.CreditLimit) error
	GetByID(id uint, branchID uint, role string) (*domain.CreditLimit, error)
	List(branchID uint, role string) ([]domain.CreditLimit, error)
	GetNextSequence(docType string, year, month int) (int, error)
	Update(cl *domain.CreditLimit) error
	Delete(id uint, branchID uint, role string) error
}

type repositoryImpl struct {
	base *repository.Repository
}

func NewRepository(base *repository.Repository) CreditLimitRepository {
	return &repositoryImpl{base: base}
}

func (r *repositoryImpl) Create(cl *domain.CreditLimit) error {
	return r.base.GetDB().Create(cl).Error
}

func (r *repositoryImpl) GetByID(id uint, branchID uint, role string) (*domain.CreditLimit, error) {
	var cl domain.CreditLimit
	q := r.base.GetDB()
	if role != "superadmin" && branchID > 0 {
		q = q.Where("branch_id = ?", branchID)
	}
	err := q.First(&cl, id).Error
	return &cl, err
}

func (r *repositoryImpl) List(branchID uint, role string) ([]domain.CreditLimit, error) {
	var list []domain.CreditLimit
	q := r.base.GetDB().Order("created_at desc")
	if role != "superadmin" && branchID > 0 {
		q = q.Where("branch_id = ?", branchID)
	}
	err := q.Find(&list).Error
	return list, err
}

func (r *repositoryImpl) GetNextSequence(docType string, year, month int) (int, error) {
	return r.base.GetNextSequence(docType, year, month)
}

func (r *repositoryImpl) Update(cl *domain.CreditLimit) error {
	return r.base.GetDB().Save(cl).Error
}

func (r *repositoryImpl) Delete(id uint, branchID uint, role string) error {
	q := r.base.GetDB().Where("id = ?", id)
	if role != "superadmin" && branchID > 0 {
		q = q.Where("branch_id = ?", branchID)
	}
	return q.Delete(&domain.CreditLimit{}).Error
}
