package service

import (
	"context"
	"errors"
	"strings"

	vulnmodel "security-center-backend/internal/modules/vuln/model"
	"security-center-backend/internal/modules/vuln/repository"
)

type SourceListQuery struct {
	Page       int
	PageSize   int
	Query      string
	SystemOnly *bool
}

type SourceListResult struct {
	Items []vulnmodel.Source `json:"items"`
	Total int64              `json:"total"`
}

type SourceService struct {
	repo repository.SourceRepository
}

func NewSourceService(repo repository.SourceRepository) *SourceService {
	return &SourceService{repo: repo}
}

func (s *SourceService) List(ctx context.Context, query SourceListQuery) (*SourceListResult, error) {
	items, total, err := s.repo.List(ctx, repository.SourceListParams{
		Page:       query.Page,
		PageSize:   query.PageSize,
		Query:      query.Query,
		SystemOnly: query.SystemOnly,
	})
	if err != nil {
		return nil, err
	}
	return &SourceListResult{Items: items, Total: total}, nil
}

func (s *SourceService) Create(ctx context.Context, src *vulnmodel.Source) error {
	if strings.TrimSpace(src.Name) == "" {
		return errors.New("name is required")
	}
	return s.repo.Create(ctx, src)
}

func (s *SourceService) Update(ctx context.Context, src *vulnmodel.Source) error {
	if src.ID == 0 {
		return errors.New("id is required")
	}
	if strings.TrimSpace(src.Name) == "" {
		return errors.New("name is required")
	}
	return s.repo.Update(ctx, src)
}

func (s *SourceService) Delete(ctx context.Context, id uint64, allowSystem bool) error {
	if id == 0 {
		return errors.New("id is required")
	}
	isSystem, err := s.repo.IsSystem(ctx, id)
	if err != nil {
		return err
	}
	if isSystem && !allowSystem {
		return errors.New("system sources cannot be deleted")
	}
	return s.repo.Delete(ctx, id)
}
