package repositories

import (
	"fmt"
	"learnsteam/learsteam-quiz-api/internal/models"

	"gorm.io/gorm"
)

type programRepository struct {
	DB *gorm.DB
}

func NewProgramRepository(db *gorm.DB) ProgramRepository {
	return &programRepository{
		DB: db,
	}
}

type ProgramRepository interface {
	List(string, string, int, int) (*[]models.Program, error)
	Total(string, string) (int64, error)

	Find(string) (*models.Program, error)
	Create(*models.Program) (*models.Program, error)
	Update(*models.Program) (*models.Program, error)
	Delete(string) error
}

func (r *programRepository) List(q string, tag string, page int, limit int) (*[]models.Program, error) {
	var programs *[]models.Program
	var err error
	offset := limit * (page - 1)
	fmt.Println("q", q)
	if q != "" {
		fmt.Println(" 1 q", q)
		err = r.DB.Offset(offset).Limit(limit).Order("created_at DESC").Where("subject LIKE ? OR course LIKE ? OR tags LIKE ?", "%"+q+"%", "%"+q+"%", "%"+q+"%").Find(&programs).Error
	} else if tag != "" {
		fmt.Println(" tag", tag)
		err = r.DB.Offset(offset).Limit(limit).Order("created_at DESC").Where("tags LIKE ?", "%"+tag+"%").Find(&programs).Error
	} else {
		fmt.Println(" query")
		err = r.DB.Offset(offset).Limit(limit).Order("created_at DESC").Find(&programs).Error
	}
	return programs, err
}

func (r *programRepository) Total(q string, tag string) (int64, error) {
	var total int64
	var err error
	if q != "" {
		err = r.DB.Model(&models.Program{}).Where("subject LIKE ? OR course LIKE ? OR tags LIKE ?", "%"+q+"%", "%"+q+"%", "%"+q+"%").Count(&total).Error
	} else if tag != "" {
		err = r.DB.Model(&models.Program{}).Where("tags LIKE ?", "%"+tag+"%").Count(&total).Error
	} else {
		err = r.DB.Model(&models.Program{}).Count(&total).Error
	}

	return total, err
}

func (r *programRepository) Find(id string) (*models.Program, error) {
	var program *models.Program
	err := r.DB.Where("id = ?", id).First(&program).Error
	return program, err
}

func (r *programRepository) Create(program *models.Program) (*models.Program, error) {
	err := r.DB.Create(&program).Error
	return program, err
}

func (r *programRepository) Update(program *models.Program) (*models.Program, error) {
	var row *models.Program
	if err := r.DB.Where("id=?", program.ID).First(&row).Error; err != nil {
		return nil, err
	}

	err := r.DB.Model(&row).Select("*").Updates(&program).Error
	return row, err
}

func (r *programRepository) Delete(id string) error {
	var program *models.Program
	if err := r.DB.Where("id=?", id).First(&program).Error; err != nil {
		return err
	}
	err := r.DB.Delete(&program).Error
	return err
}
