package files

import (
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
	"time"

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

type Service struct {
	root string
	db   *gorm.DB
}

type StoredFile struct {
	OriginalName string
	RelativePath string
	AbsolutePath string
}

// NewService 集中持有存储根目录；任何服务端本地路径都只能由该服务构造。
func NewService(root string, databases ...*gorm.DB) *Service {
	var database *gorm.DB
	if len(databases) > 0 {
		database = databases[0]
	}
	return &Service{root: root, db: database}
}

// Save 清理客户端文件名，并只返回供持久化的相对路径；绝对路径不得进入 API DTO。
func (s *Service) Save(projectID uint, originalName string, content io.Reader) (StoredFile, error) {
	cleanName := filepath.Base(strings.ReplaceAll(strings.TrimSpace(originalName), "\\", "/"))
	if cleanName == "." || cleanName == "" {
		cleanName = "upload.bin"
	}
	relative := filepath.ToSlash(filepath.Join("projects", fmt.Sprint(projectID), fmt.Sprintf("%d-%s", time.Now().UnixNano(), cleanName)))
	absolute := filepath.Join(s.root, filepath.FromSlash(relative))
	if err := os.MkdirAll(filepath.Dir(absolute), 0o755); err != nil {
		return StoredFile{}, err
	}
	file, err := os.Create(absolute)
	if err != nil {
		return StoredFile{}, err
	}
	defer file.Close()
	if _, err := io.Copy(file, content); err != nil {
		return StoredFile{}, err
	}
	return StoredFile{OriginalName: cleanName, RelativePath: relative, AbsolutePath: absolute}, nil
}

func (s *Service) database() *gorm.DB {
	if s.db != nil {
		return s.db
	}
	return models.DBService
}

var (
	ErrSourceTitleRequired = errors.New("source title is required")
	ErrSourcePathRequired  = errors.New("source file path is required")
)

// CreateSource 只持久化 Save 产生的相对路径，不接受 handler 自行拼接本地路径。
func (s *Service) CreateSource(ownerID uint, project *models.SenlinAgentProject, title string, stored StoredFile) (*models.SenlinAgentSource, error) {
	title = strings.TrimSpace(title)
	if title == "" {
		title = stored.OriginalName
	}
	if title == "" {
		return nil, ErrSourceTitleRequired
	}
	relativePath := filepath.ToSlash(strings.TrimSpace(stored.RelativePath))
	if relativePath == "" || filepath.IsAbs(relativePath) {
		return nil, ErrSourcePathRequired
	}
	source := &models.SenlinAgentSource{
		ProjectID: project.ID, ProjectIdentity: project.Identity, CreatedBy: ownerID,
		Kind: "file", Title: title, FilePath: relativePath,
	}
	if err := s.database().Create(source).Error; err != nil {
		return nil, err
	}
	return source, nil
}
