package service

import (
	"context"
	"fmt"
	"time"

	"github.com/TopherMayor/unified-media-manager/internal/db"
)

type RootFolder struct {
	ID        int64      `json:"id"`
	Path      string     `json:"path"`
	MediaType string     `json:"media_type"`
	FreeSpace *int64     `json:"free_space,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
}

type CreateRootFolderRequest struct {
	Path      string `json:"path"`
	MediaType string `json:"media_type"`
}

type RootFolderService struct {
	db *db.DB
}

func NewRootFolderService(database *db.DB) *RootFolderService {
	return &RootFolderService{db: database}
}

func (s *RootFolderService) List(ctx context.Context) ([]RootFolder, error) {
	rows, err := s.db.Pool.Query(ctx,
		"SELECT id, path, media_type, free_space, created_at FROM root_folders ORDER BY path")
	if err != nil {
		return nil, fmt.Errorf("list root folders: %w", err)
	}
	defer rows.Close()

	var folders []RootFolder
	for rows.Next() {
		var f RootFolder
		if err := rows.Scan(&f.ID, &f.Path, &f.MediaType, &f.FreeSpace, &f.CreatedAt); err != nil {
			return nil, fmt.Errorf("scan root folder: %w", err)
		}
		folders = append(folders, f)
	}
	return folders, nil
}

func (s *RootFolderService) Create(ctx context.Context, req CreateRootFolderRequest) (int64, error) {
	if req.Path == "" {
		return 0, fmt.Errorf("path is required")
	}
	if req.MediaType == "" {
		return 0, fmt.Errorf("media_type is required")
	}

	var id int64
	err := s.db.Pool.QueryRow(ctx,
		"INSERT INTO root_folders (path, media_type, created_at) VALUES ($1, $2, NOW()) RETURNING id",
		req.Path, req.MediaType).Scan(&id)
	if err != nil {
		return 0, fmt.Errorf("create root folder: %w", err)
	}
	return id, nil
}

func (s *RootFolderService) Delete(ctx context.Context, id int64) error {
	tag, err := s.db.Pool.Exec(ctx, "DELETE FROM root_folders WHERE id = $1", id)
	if err != nil {
		return fmt.Errorf("delete root folder: %w", err)
	}
	if tag.RowsAffected() == 0 {
		return fmt.Errorf("root folder not found")
	}
	return nil
}
