package service

import (
	"context"
	"encoding/json"
	"kra/internal/biz/system"
	"time"

	"kra/internal/service/dto"
)

type AnnouncementInput struct {
	ID          uint
	Title       string
	Content     string
	UserID      *int
	Attachments json.RawMessage
}

type AnnouncementService struct{ uc *system.AnnouncementUsecase }

func NewAnnouncementService(uc *system.AnnouncementUsecase) *AnnouncementService {
	return &AnnouncementService{uc: uc}
}

func announcementDTO(item *system.Announcement) *dto.AnnouncementResponse {
	return &dto.AnnouncementResponse{ID: item.ID, CreatedAt: item.CreatedAt, UpdatedAt: item.UpdatedAt, DeletedAt: nil, Title: item.Title, Content: item.Content, UserID: item.UserID, Attachments: json.RawMessage(item.Attachments)}
}

func announcementDO(in AnnouncementInput) *system.Announcement {
	return &system.Announcement{ID: in.ID, Title: in.Title, Content: in.Content, UserID: in.UserID, Attachments: in.Attachments}
}

func (s *AnnouncementService) Create(ctx context.Context, in AnnouncementInput) error {
	return s.uc.Create(ctx, announcementDO(in))
}

func (s *AnnouncementService) Update(ctx context.Context, in AnnouncementInput) error {
	return s.uc.Update(ctx, announcementDO(in))
}

func (s *AnnouncementService) Delete(ctx context.Context, id string) error {
	return s.uc.Delete(ctx, id)
}

func (s *AnnouncementService) DeleteByIDs(ctx context.Context, ids []string) error {
	return s.uc.DeleteByIDs(ctx, ids)
}

func (s *AnnouncementService) Find(ctx context.Context, id string) (*dto.AnnouncementResponse, error) {
	item, err := s.uc.Find(ctx, id)
	if err != nil {
		return nil, err
	}
	return announcementDTO(item), nil
}

func (s *AnnouncementService) List(ctx context.Context, page, pageSize int, start, end *time.Time) ([]*dto.AnnouncementResponse, int64, error) {
	items, total, err := s.uc.List(ctx, system.AnnouncementFilter{Page: page, PageSize: pageSize, StartCreatedAt: start, EndCreatedAt: end})
	if err != nil {
		return nil, 0, err
	}
	result := make([]*dto.AnnouncementResponse, 0, len(items))
	for _, item := range items {
		result = append(result, announcementDTO(item))
	}
	return result, total, nil
}

func (s *AnnouncementService) UserOptions(ctx context.Context) ([]*dto.SelectOptionResponse, error) {
	items, err := s.uc.UserOptions(ctx)
	if err != nil {
		return nil, err
	}
	result := make([]*dto.SelectOptionResponse, 0, len(items))
	for _, item := range items {
		result = append(result, &dto.SelectOptionResponse{Label: item.Label, Value: item.Value})
	}
	return result, nil
}
