package announcement

import (
	"context"
	"errors"

	"gorm.io/gorm"
)

type Service struct {
	repo *Repository
}

func NewService(repo *Repository) *Service {
	return &Service{repo: repo}
}

var (
	ErrNotFound       = errors.New("公告不存在")
	ErrInvalidRequest = errors.New("请求参数不正确")
	ErrUnauthorized   = errors.New("未授权")
)

// List 获取公告列表（前台用户）
func (s *Service) List(ctx context.Context, query AnnouncementListQuery) (*PaginatedResult, error) {
	if query.Page < 1 {
		query.Page = 1
	}
	if query.PageSize < 1 {
		query.PageSize = 20
	}
	if query.PageSize > 100 {
		query.PageSize = 100
	}

	return s.repo.List(ctx, query)
}

// GetByID 获取公告详情
func (s *Service) GetByID(ctx context.Context, id uint64) (*AnnouncementDTO, error) {
	dto, err := s.repo.GetByID(ctx, id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, ErrNotFound
		}
		return nil, err
	}
	return dto, nil
}

// AdminList 管理员获取公告列表
func (s *Service) AdminList(ctx context.Context, query AnnouncementListQuery) (*PaginatedResult, error) {
	if query.Page < 1 {
		query.Page = 1
	}
	if query.PageSize < 1 {
		query.PageSize = 20
	}
	if query.PageSize > 100 {
		query.PageSize = 100
	}

	return s.repo.AdminList(ctx, query)
}

// AdminGetByID 管理员获取公告详情
func (s *Service) AdminGetByID(ctx context.Context, id uint64) (*AnnouncementDTO, error) {
	dto, err := s.repo.AdminGetByID(ctx, id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, ErrNotFound
		}
		return nil, err
	}
	return dto, nil
}

// Create 创建公告
func (s *Service) Create(ctx context.Context, req CreateAnnouncementRequest, createdBy uint64) (*AnnouncementDTO, error) {
	return s.repo.Create(ctx, req, createdBy)
}

// Update 更新公告
func (s *Service) Update(ctx context.Context, id uint64, req UpdateAnnouncementRequest) (*AnnouncementDTO, error) {
	return s.repo.Update(ctx, id, req)
}

// Publish 发布公告
func (s *Service) Publish(ctx context.Context, id uint64) error {
	return s.repo.Publish(ctx, id)
}

// Archive 归档公告
func (s *Service) Archive(ctx context.Context, id uint64) error {
	return s.repo.Archive(ctx, id)
}

// Unarchive 取消归档公告
func (s *Service) Unarchive(ctx context.Context, id uint64) error {
	return s.repo.Unarchive(ctx, id)
}

// Delete 删除公告
func (s *Service) Delete(ctx context.Context, id uint64) error {
	return s.repo.Delete(ctx, id)
}
