package service

import (
	"errors"
	"narasi-ahli-be/app/database/entity"
	"narasi-ahli-be/app/module/notifications/repository"
	"narasi-ahli-be/app/module/notifications/response"
)

type notificationsService struct {
	Repo repository.NotificationsRepository
}

func NewNotificationsService(repo repository.NotificationsRepository) NotificationsService {
	return &notificationsService{Repo: repo}
}
type NotificationsService interface {
	Create(sentTo int, sendBy int, sendByName string, message string) (*response.NotificationResponse, error)
	ListBySentTo(sentTo int, page int, limit int, isRead *bool) ([]response.NotificationResponse, int64, error)
	MarkRead(id uint64) error
	Delete(id uint64) error
}

func (s *notificationsService) Create(sentTo int, sendBy int, sendByName string, message string) (*response.NotificationResponse, error) {
	if sentTo <= 0 {
		return nil, errors.New("sentTo is required")
	}
	if sendBy <= 0 {
		return nil, errors.New("sendBy is required")
	}
	if sendByName == "" {
		return nil, errors.New("sendByName is required")
	}
	if message == "" {
		return nil, errors.New("message is required")
	}

	data := entity.Notifications{
		SentTo:     sentTo,
		SendBy:     sendBy,
		SendByName: sendByName,
		Message:    message,
		IsRead:     false,
		IsActive:   true,
	}

	if err := s.Repo.Create(&data); err != nil {
		return nil, err
	}

	return &response.NotificationResponse{
		ID:         data.ID,
		SentTo:     data.SentTo,
		SendBy:     data.SendBy,
		SendByName: data.SendByName,
		Message:    data.Message,
		IsRead:     data.IsRead,
		IsActive:   data.IsActive,
		CreatedAt:  data.CreatedAt,
		UpdatedAt:  data.UpdatedAt,
	}, nil
}

func (s *notificationsService) ListBySentTo(sentTo int, page int, limit int, isRead *bool) ([]response.NotificationResponse, int64, error) {
	if sentTo <= 0 {
		return nil, 0, errors.New("sentTo is required")
	}

	rows, total, err := s.Repo.ListBySentTo(sentTo, page, limit, isRead)
	if err != nil {
		return nil, 0, err
	}

	result := make([]response.NotificationResponse, 0)
	for _, item := range rows {
		result = append(result, response.NotificationResponse{
			ID:         item.ID,
			SentTo:     item.SentTo,
			SendBy:     item.SendBy,
			SendByName: item.SendByName,
			Message:    item.Message,
			IsRead:     item.IsRead,
			IsActive:   item.IsActive,
			CreatedAt:  item.CreatedAt,
			UpdatedAt:  item.UpdatedAt,
		})
	}

	return result, total, nil
}

func (s *notificationsService) MarkRead(id uint64) error {
	old, err := s.Repo.FindById(id)
	if err != nil {
		return err
	}

	if old.IsActive == false {
		return errors.New("notification already deleted")
	}

	return s.Repo.MarkRead(id)
}

func (s *notificationsService) Delete(id uint64) error {
	return s.Repo.Delete(id)
}
