package repository

import (
	"campaign-pool-be/app/database"
	"campaign-pool-be/app/database/entity"
	"campaign-pool-be/app/module/chat/request"
)

type chatScheduleFileRepository struct {
	DB *database.Database
}

type ChatScheduleFileRepository interface {
	// File CRUD operations
	CreateChatScheduleFile(file *entity.ChatScheduleFiles) (result *entity.ChatScheduleFiles, err error)
	GetChatScheduleFiles(req request.ChatScheduleFileQueryRequest) (files []*entity.ChatScheduleFiles, err error)
	GetChatScheduleFileByID(id uint) (file *entity.ChatScheduleFiles, err error)
	GetChatScheduleFileByFilename(filename string) (file *entity.ChatScheduleFiles, err error)
	UpdateChatScheduleFile(id uint, file *entity.ChatScheduleFiles) (err error)
	DeleteChatScheduleFile(id uint) (err error)
}

func NewChatScheduleFileRepository(db *database.Database) ChatScheduleFileRepository {
	return &chatScheduleFileRepository{
		DB: db,
	}
}

// CreateChatScheduleFile - Create a new chat schedule file
func (_i *chatScheduleFileRepository) CreateChatScheduleFile(file *entity.ChatScheduleFiles) (result *entity.ChatScheduleFiles, err error) {
	err = _i.DB.DB.Create(file).Error
	if err != nil {
		return nil, err
	}

	err = _i.DB.DB.First(&result, file.ID).Error
	return
}

// GetChatScheduleFiles - Get files for chat schedule with filters
func (_i *chatScheduleFileRepository) GetChatScheduleFiles(req request.ChatScheduleFileQueryRequest) (files []*entity.ChatScheduleFiles, err error) {
	query := _i.DB.DB.Model(&entity.ChatScheduleFiles{})

	// Apply filters
	if req.ChatScheduleID != nil {
		query = query.Where("chat_schedule_id = ?", *req.ChatScheduleID)
	}

	if req.FileType != nil {
		query = query.Where("file_type = ?", *req.FileType)
	}

	if req.IsRequired != nil {
		query = query.Where("is_required = ?", *req.IsRequired)
	}

	// Order by created_at desc (newest first)
	query = query.Order("created_at DESC")

	err = query.Find(&files).Error
	return
}

// GetChatScheduleFileByID - Get a specific chat schedule file
func (_i *chatScheduleFileRepository) GetChatScheduleFileByID(id uint) (file *entity.ChatScheduleFiles, err error) {
	err = _i.DB.DB.First(&file, id).Error
	return
}

// UpdateChatScheduleFile - Update a chat schedule file
func (_i *chatScheduleFileRepository) UpdateChatScheduleFile(id uint, file *entity.ChatScheduleFiles) (err error) {
	err = _i.DB.DB.Model(&entity.ChatScheduleFiles{}).Where("id = ?", id).Updates(file).Error
	return
}

// GetChatScheduleFileByFilename - Get a chat schedule file by filename
func (_i *chatScheduleFileRepository) GetChatScheduleFileByFilename(filename string) (file *entity.ChatScheduleFiles, err error) {
	err = _i.DB.DB.Where("file_name = ?", filename).First(&file).Error
	return
}

// DeleteChatScheduleFile - Delete a chat schedule file
func (_i *chatScheduleFileRepository) DeleteChatScheduleFile(id uint) (err error) {
	err = _i.DB.DB.Delete(&entity.ChatScheduleFiles{}, id).Error
	return
}
