package repository

import (
	"context"
	"fmt"
	"time"

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

type MarketingRepository interface {
	repository.BaseRepository[entity.Marketing]
	IdExists(ctx context.Context, id uint) (bool, error)
	GetNextSequence(ctx context.Context) (uint, error)
	NextSoNumber(ctx context.Context, tx *gorm.DB) (string, error)
	GetProgressRows(ctx context.Context, startDate, endDate time.Time, allowedLocationIDs []uint, restrict bool) ([]exportprogress.Row, error)
}

type MarketingRepositoryImpl struct {
	*repository.BaseRepositoryImpl[entity.Marketing]
}

func NewMarketingRepository(db *gorm.DB) MarketingRepository {
	return &MarketingRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.Marketing](db),
	}
}

func (r *MarketingRepositoryImpl) IdExists(ctx context.Context, id uint) (bool, error) {
	return repository.Exists[entity.Marketing](ctx, r.DB(), id)
}

func (r *MarketingRepositoryImpl) GetNextSequence(ctx context.Context) (uint, error) {
	var maxID uint
	if err := r.DB().WithContext(ctx).Model(&entity.Marketing{}).Select("COALESCE(MAX(id), 0)").Scan(&maxID).Error; err != nil {
		return 0, err
	}
	return maxID + 1, nil
}

func (r *MarketingRepositoryImpl) NextSoNumber(ctx context.Context, tx *gorm.DB) (string, error) {
	db := tx
	if db == nil {
		db = r.DB()
	}

	var soNumber string
	err := db.WithContext(ctx).
		Raw("SELECT generate_so_number()").
		Scan(&soNumber).Error

	if err != nil {
		return "", fmt.Errorf("failed to generate SO number: %w", err)
	}

	return soNumber, nil
}

func (r *MarketingRepositoryImpl) GetProgressRows(ctx context.Context, startDate, endDate time.Time, allowedLocationIDs []uint, restrict bool) ([]exportprogress.Row, error) {
	const unassignedSQL = "'" + exportprogress.UnassignedKandangName + "'"
	subQuery := r.DB().WithContext(ctx).
		Table("marketings AS m").
		Select(`
			DISTINCT m.id AS marketing_id,
			'Marketings' AS module,
			COALESCE(pf.flock_name, loc.name, 'Unknown Farm') AS farm_name,
			COALESCE(k.name, `+unassignedSQL+`, 'Unknown Kandang') AS kandang_name,
			CAST(DATE(m.so_date) AS TEXT) AS activity_date
		`).
		Joins("JOIN marketing_products mp ON mp.marketing_id = m.id").
		Joins("JOIN product_warehouses pw ON pw.id = mp.product_warehouse_id").
		Joins("JOIN warehouses w ON w.id = pw.warehouse_id").
		Joins("LEFT JOIN project_flock_kandangs pfk ON pfk.id = pw.project_flock_kandang_id").
		Joins("LEFT JOIN project_flocks pf ON pf.id = pfk.project_flock_id").
		Joins("LEFT JOIN kandangs k ON k.id = COALESCE(pfk.kandang_id, w.kandang_id)").
		Joins("LEFT JOIN locations loc ON loc.id = COALESCE(k.location_id, w.location_id)").
		Where("m.deleted_at IS NULL").
		Where("DATE(m.so_date) >= DATE(?)", startDate).
		Where("DATE(m.so_date) <= DATE(?)", endDate)

	if restrict {
		if len(allowedLocationIDs) == 0 {
			return []exportprogress.Row{}, nil
		}
		subQuery = subQuery.Where("w.location_id IN ?", allowedLocationIDs)
	}

	type progressRowResult struct {
		Module       string
		FarmName     string
		KandangName  string
		ActivityDate string
		Count        int
	}
	scanned := make([]progressRowResult, 0)
	err := r.DB().WithContext(ctx).
		Table("(?) AS progress_rows", subQuery).
		Select("module, farm_name, kandang_name, activity_date, COUNT(*) AS count").
		Group("module, farm_name, kandang_name, activity_date").
		Order("activity_date ASC, farm_name ASC, kandang_name ASC").
		Scan(&scanned).Error
	if err != nil {
		return nil, err
	}

	rows := make([]exportprogress.Row, 0, len(scanned))
	for _, item := range scanned {
		activityDate, err := exportprogress.ParseActivityDate(item.ActivityDate)
		if err != nil {
			return nil, err
		}
		rows = append(rows, exportprogress.Row{
			Module:       item.Module,
			FarmName:     item.FarmName,
			KandangName:  item.KandangName,
			ActivityDate: activityDate,
			Count:        item.Count,
		})
	}
	return rows, nil
}
