package repository

import (
	"narasi-ahli-be/app/database"
	"narasi-ahli-be/app/database/entity"
)

type notificationsRepository struct {
	DB *database.Database
}

type NotificationsRepository interface {
	Create(data *entity.Notifications) error
	FindById(id uint64) (*entity.Notifications, error)
	ListBySentTo(sentTo int, page int, limit int, isRead *bool) ([]entity.Notifications, int64, error)
	MarkRead(id uint64) error
	Delete(id uint64) error
}

func NewNotificationsRepository(db *database.Database) NotificationsRepository {
	return &notificationsRepository{
		DB: db,
	}
}

func (_i *notificationsRepository) Create(data *entity.Notifications) error {
	return _i.DB.DB.Create(data).Error
}

func (_i *notificationsRepository) FindById(id uint64) (*entity.Notifications, error) {
	var notif entity.Notifications
	err := _i.DB.DB.Where("id = ?", id).First(&notif).Error
	if err != nil {
		return nil, err
	}
	return &notif, nil
}

func (_i *notificationsRepository) ListBySentTo(sentTo int, page int, limit int, isRead *bool) ([]entity.Notifications, int64, error) {
	var data []entity.Notifications
	var total int64

	if page <= 0 {
		page = 1
	}
	if limit <= 0 {
		limit = 10
	}

	q := _i.DB.DB.Model(&entity.Notifications{}).
		Where("sent_to = ?", sentTo).
		Where("is_active = ?", true)

	if isRead != nil {
		q = q.Where("is_read = ?", *isRead)
	}

	// count
	if err := q.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// pagination
	offset := (page - 1) * limit
	if err := q.Order("created_at DESC").
		Limit(limit).
		Offset(offset).
		Find(&data).Error; err != nil {
		return nil, 0, err
	}

	return data, total, nil
}

func (_i *notificationsRepository) MarkRead(id uint64) error {
	return _i.DB.DB.Model(&entity.Notifications{}).
		Where("id = ? AND is_active = true", id).
		Update("is_read", true).Error
}

func (_i *notificationsRepository) Delete(id uint64) error {
	return _i.DB.DB.Model(&entity.Notifications{}).
		Where("id = ?", id).
		Update("is_active", false).Error
}
