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 ProductionStandardDetailRepository interface {
	repository.BaseRepository[entity.ProductionStandardDetail]
	IdExists(ctx context.Context, id uint) (bool, error)
	GetByProductionStandardID(ctx context.Context, productionStandardId uint) ([]entity.ProductionStandardDetail, error)
	GetByStandardIDAndWeek(ctx context.Context, standardId uint, week int) (*entity.ProductionStandardDetail, error)
	DeleteByProductionStandardID(ctx context.Context, productionStandardId uint) error
}

type ProductionStandardDetailRepositoryImpl struct {
	*repository.BaseRepositoryImpl[entity.ProductionStandardDetail]
	db *gorm.DB
}

func NewProductionStandardDetailRepository(db *gorm.DB) ProductionStandardDetailRepository {
	return &ProductionStandardDetailRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.ProductionStandardDetail](db),
		db:                 db,
	}
}

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

func (r *ProductionStandardDetailRepositoryImpl) GetByProductionStandardID(ctx context.Context, productionStandardId uint) ([]entity.ProductionStandardDetail, error) {
	var details []entity.ProductionStandardDetail
	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 *ProductionStandardDetailRepositoryImpl) GetByStandardIDAndWeek(ctx context.Context, standardId uint, week int) (*entity.ProductionStandardDetail, error) {
	var detail entity.ProductionStandardDetail
	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 *ProductionStandardDetailRepositoryImpl) DeleteByProductionStandardID(ctx context.Context, productionStandardId uint) error {
	return r.db.WithContext(ctx).
		Where("production_standard_id = ?", productionStandardId).
		Delete(&entity.ProductionStandardDetail{}).Error
}
