package repository

import (
	"context"

	"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	"gorm.io/gorm"
)

type StandardGrowthDetailRepository interface {
	repository.BaseRepository[entity.StandardGrowthDetail]
	IdExists(ctx context.Context, id uint) (bool, error)
	GetByProductionStandardID(ctx context.Context, productionStandardId uint) ([]entity.StandardGrowthDetail, error)
	GetByStandardIDAndWeek(ctx context.Context, standardId uint, week int) (*entity.StandardGrowthDetail, error)
	DeleteByProductionStandardID(ctx context.Context, productionStandardId uint) error
}

type StandardGrowthDetailRepositoryImpl struct {
	*repository.BaseRepositoryImpl[entity.StandardGrowthDetail]
	db *gorm.DB
}

func NewStandardGrowthDetailRepository(db *gorm.DB) StandardGrowthDetailRepository {
	return &StandardGrowthDetailRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.StandardGrowthDetail](db),
		db:                 db,
	}
}

func (r *StandardGrowthDetailRepositoryImpl) IdExists(ctx context.Context, id uint) (bool, error) {
	return repository.Exists[entity.StandardGrowthDetail](ctx, r.db, id)
}

func (r *StandardGrowthDetailRepositoryImpl) GetByProductionStandardID(ctx context.Context, productionStandardId uint) ([]entity.StandardGrowthDetail, error) {
	var details []entity.StandardGrowthDetail
	err := r.db.WithContext(ctx).
		Where("production_standard_id = ?", productionStandardId).
		Order("week ASC").
		Find(&details).Error
	if err != nil {
		return nil, err
	}
	return details, nil
}

func (r *StandardGrowthDetailRepositoryImpl) GetByStandardIDAndWeek(ctx context.Context, standardId uint, week int) (*entity.StandardGrowthDetail, error) {
	var detail entity.StandardGrowthDetail
	err := r.db.WithContext(ctx).
		Where("production_standard_id = ?", standardId).
		Where("week = ?", week).
		First(&detail).Error
	if err != nil {
		return nil, err
	}
	return &detail, nil
}

func (r *StandardGrowthDetailRepositoryImpl) DeleteByProductionStandardID(ctx context.Context, productionStandardId uint) error {
	return r.db.WithContext(ctx).
		Where("production_standard_id = ?", productionStandardId).
		Delete(&entity.StandardGrowthDetail{}).Error
}
