package repository

import (
	"campaign-pool-be/app/database"
	"campaign-pool-be/app/database/entity"
	"campaign-pool-be/app/module/research_journals/request"
	"campaign-pool-be/utils/paginator"
)

type researchJournalsRepository struct {
	DB *database.Database
}

type ResearchJournalsRepository interface {
	GetAll(userId uint, req request.ResearchJournalsQueryRequest) (researchJournals []*entity.ResearchJournals, paging paginator.Pagination, err error)
	FindOneByUserAndId(userId uint, id uint) (researchJournal *entity.ResearchJournals, err error)
	Create(researchJournal *entity.ResearchJournals) (result *entity.ResearchJournals, err error)
	Update(userId uint, id uint, researchJournal *entity.ResearchJournals) (err error)
	Delete(userId uint, id uint) (err error)
}

func NewResearchJournalsRepository(db *database.Database) ResearchJournalsRepository {
	return &researchJournalsRepository{
		DB: db,
	}
}

func (_i *researchJournalsRepository) GetAll(userId uint, req request.ResearchJournalsQueryRequest) (researchJournals []*entity.ResearchJournals, paging paginator.Pagination, err error) {
	query := _i.DB.DB.Where("user_id = ?", userId)

	// Apply filters
	if req.JournalTitle != nil {
		query = query.Where("journal_title ILIKE ?", "%"+*req.JournalTitle+"%")
	}
	if req.Publisher != nil {
		query = query.Where("publisher ILIKE ?", "%"+*req.Publisher+"%")
	}
	if req.PublishedYear != nil {
		query = query.Where("EXTRACT(YEAR FROM published_date) = ?", *req.PublishedYear)
	}

	// Include user relationship
	query = query.Preload("User")

	// Order by published date desc (most recent first), then by created_at desc
	query = query.Order("published_date DESC NULLS LAST, created_at DESC")

	// Apply pagination
	var count int64
	query.Count(&count)
	req.Pagination.Count = count
	req.Pagination = paginator.Paging(req.Pagination)

	err = query.Offset(req.Pagination.Offset).Limit(req.Pagination.Limit).Find(&researchJournals).Error
	paging = *req.Pagination

	return
}

func (_i *researchJournalsRepository) FindOneByUserAndId(userId uint, id uint) (researchJournal *entity.ResearchJournals, err error) {
	err = _i.DB.DB.Where("user_id = ? AND id = ?", userId, id).Preload("User").First(&researchJournal).Error
	return
}

func (_i *researchJournalsRepository) Create(researchJournal *entity.ResearchJournals) (result *entity.ResearchJournals, err error) {
	err = _i.DB.DB.Create(researchJournal).Error
	if err != nil {
		return nil, err
	}

	// Reload with relationships
	err = _i.DB.DB.Preload("User").First(&result, researchJournal.ID).Error
	return
}

func (_i *researchJournalsRepository) Update(userId uint, id uint, researchJournal *entity.ResearchJournals) (err error) {
	err = _i.DB.DB.Where("user_id = ? AND id = ?", userId, id).Updates(researchJournal).Error
	return
}

func (_i *researchJournalsRepository) Delete(userId uint, id uint) (err error) {
	err = _i.DB.DB.Where("user_id = ? AND id = ?", userId, id).Delete(&entity.ResearchJournals{}).Error
	return
}
