package services

import (
	"github.com/treytartt/honeydue-api/internal/models"
	"gorm.io/gorm"
)

// FileOwnershipService checks whether a user owns a file referenced by URL.
// It queries task completion images, document files, and document images
// to determine ownership through residence access.
type FileOwnershipService struct {
	db *gorm.DB
}

// NewFileOwnershipService creates a new FileOwnershipService
func NewFileOwnershipService(db *gorm.DB) *FileOwnershipService {
	return &FileOwnershipService{db: db}
}

// IsFileOwnedByUser checks if the given file URL belongs to a record
// that the user has access to (via residence membership).
func (s *FileOwnershipService) IsFileOwnedByUser(fileURL string, userID uint) (bool, error) {
	// Check task completion images: image_url -> completion -> task -> residence -> user access
	var completionImageCount int64
	err := s.db.Model(&models.TaskCompletionImage{}).
		Joins("JOIN task_taskcompletion ON task_taskcompletion.id = task_taskcompletionimage.completion_id").
		Joins("JOIN task_task ON task_task.id = task_taskcompletion.task_id").
		Joins("JOIN residence_residence_users ON residence_residence_users.residence_id = task_task.residence_id").
		Where("task_taskcompletionimage.image_url = ? AND residence_residence_users.user_id = ?", fileURL, userID).
		Count(&completionImageCount).Error
	if err != nil {
		return false, err
	}
	if completionImageCount > 0 {
		return true, nil
	}

	// Check document files: file_url -> document -> residence -> user access
	var documentCount int64
	err = s.db.Model(&models.Document{}).
		Joins("JOIN residence_residence_users ON residence_residence_users.residence_id = task_document.residence_id").
		Where("task_document.file_url = ? AND residence_residence_users.user_id = ?", fileURL, userID).
		Count(&documentCount).Error
	if err != nil {
		return false, err
	}
	if documentCount > 0 {
		return true, nil
	}

	// Check document images: image_url -> document_image -> document -> residence -> user access
	var documentImageCount int64
	err = s.db.Model(&models.DocumentImage{}).
		Joins("JOIN task_document ON task_document.id = task_documentimage.document_id").
		Joins("JOIN residence_residence_users ON residence_residence_users.residence_id = task_document.residence_id").
		Where("task_documentimage.image_url = ? AND residence_residence_users.user_id = ?", fileURL, userID).
		Count(&documentImageCount).Error
	if err != nil {
		return false, err
	}
	if documentImageCount > 0 {
		return true, nil
	}

	return false, nil
}
