package service

import (
	"context"
	"fmt"

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

type Tag struct {
	ID    int64  `json:"id"`
	Name  string `json:"name"`
	Color string `json:"color"`
}

type CreateTagRequest struct {
	Name  string `json:"name"`
	Color string `json:"color,omitempty"`
}

type TagService struct {
	db *db.DB
}

func NewTagService(database *db.DB) *TagService {
	return &TagService{db: database}
}

func (s *TagService) List(ctx context.Context) ([]Tag, error) {
	rows, err := s.db.Pool.Query(ctx,
		"SELECT id, name, COALESCE(color, '#6366f1') FROM tags ORDER BY name")
	if err != nil {
		return nil, fmt.Errorf("list tags: %w", err)
	}
	defer rows.Close()

	var tags []Tag
	for rows.Next() {
		var t Tag
		if err := rows.Scan(&t.ID, &t.Name, &t.Color); err != nil {
			return nil, fmt.Errorf("scan tag: %w", err)
		}
		tags = append(tags, t)
	}
	return tags, nil
}

func (s *TagService) Create(ctx context.Context, req CreateTagRequest) (int64, error) {
	if req.Name == "" {
		return 0, fmt.Errorf("name is required")
	}
	color := req.Color
	if color == "" {
		color = "#6366f1"
	}

	var id int64
	err := s.db.Pool.QueryRow(ctx,
		"INSERT INTO tags (name, color) VALUES ($1, $2) RETURNING id",
		req.Name, color).Scan(&id)
	if err != nil {
		return 0, fmt.Errorf("create tag: %w", err)
	}
	return id, nil
}

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