package projects

import (
	"errors"
	"strings"

	"gorm.io/gorm"
	"senlinai-agent/backend/internal/models"
)

func (s *Service) CreateCronPlan(ownerID uint, projectID uint, input CreateCronPlanInput) (*models.SenlinAgentCronPlan, error) {
	if err := ensureProjectOwner(ownerID, projectID); err != nil {
		return nil, err
	}
	title := strings.TrimSpace(input.Title)
	if title == "" {
		return nil, errors.New("cron plan title is required")
	}
	schedule := strings.TrimSpace(input.Schedule)
	if schedule == "" {
		return nil, errors.New("cron schedule is required")
	}
	plan := &models.SenlinAgentCronPlan{
		ProjectID: projectID, CreatedBy: ownerID, Title: title, Schedule: schedule,
		Enabled: input.Enabled, NextRunAt: input.NextRunAt, LastResult: "Not run yet",
	}
	return plan, models.DBService.Create(plan).Error
}

func (s *Service) CreateProjectTag(ownerID uint, projectID uint, name string) (*models.SenlinAgentTag, error) {
	if err := ensureProjectOwner(ownerID, projectID); err != nil {
		return nil, err
	}
	return s.CreateTag(projectID, name)
}

func (s *Service) CreateTag(projectID uint, name string) (*models.SenlinAgentTag, error) {
	name = strings.TrimSpace(name)
	if name == "" {
		return nil, errors.New("tag name is required")
	}
	var existing models.SenlinAgentTag
	err := models.DBService.Where("project_id = ? AND name = ?", projectID, name).First(&existing).Error
	if err == nil {
		return &existing, nil
	}
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}
	tag := &models.SenlinAgentTag{ProjectID: projectID, Name: name}
	return tag, models.DBService.Create(tag).Error
}

func (s *Service) ListProjectTags(ownerID uint, projectID uint) ([]models.SenlinAgentTag, error) {
	if err := ensureProjectOwner(ownerID, projectID); err != nil {
		return nil, err
	}
	return s.ListTags(projectID)
}

func (s *Service) ListTags(projectID uint) ([]models.SenlinAgentTag, error) {
	var tags []models.SenlinAgentTag
	err := models.DBService.Where("project_id = ?", projectID).Order("name asc").Find(&tags).Error
	return tags, err
}

func ensureProjectOwner(ownerID uint, projectID uint) error {
	var count int64
	if err := models.DBService.Model(&models.SenlinAgentProject{}).Where("id = ? AND owner_id = ?", projectID, ownerID).Count(&count).Error; err != nil {
		return err
	}
	if count == 0 {
		return gorm.ErrRecordNotFound
	}
	return nil
}
