package db

import (
	"database/sql"
	"errors"
)

func (s *Store) SaveLegacyRevision(name, raw, note, actor string) (LegacyJsonRevision, error) {
	item := LegacyJsonRevision{Name: name, Raw: raw, Note: sanitize(note), CreatedBy: firstNonEmpty(actor, "admin"), CreatedAt: Now()}
	id, err := s.insertID(`INSERT INTO legacy_json_revisions (name, raw, note, created_by, created_at) VALUES (?, ?, ?, ?, ?)`,
		item.Name, item.Raw, item.Note, item.CreatedBy, item.CreatedAt)
	if err != nil {
		return LegacyJsonRevision{}, err
	}
	item.ID = id
	return item, nil
}

func (s *Store) ListLegacyRevisions(name string, limit int) ([]LegacyJsonRevision, error) {
	if limit <= 0 || limit > 100 {
		limit = 20
	}
	rows, err := s.query(`SELECT id, name, raw, note, created_by, created_at FROM legacy_json_revisions WHERE name = ? ORDER BY id DESC LIMIT ?`, name, limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []LegacyJsonRevision{}
	for rows.Next() {
		var item LegacyJsonRevision
		if err := rows.Scan(&item.ID, &item.Name, &item.Raw, &item.Note, &item.CreatedBy, &item.CreatedAt); err != nil {
			return nil, err
		}
		items = append(items, item)
	}
	return items, rows.Err()
}

func (s *Store) GetLegacyRevision(name string, id int64) (LegacyJsonRevision, error) {
	var item LegacyJsonRevision
	err := s.queryRow(`SELECT id, name, raw, note, created_by, created_at FROM legacy_json_revisions WHERE name = ? AND id = ?`, name, id).
		Scan(&item.ID, &item.Name, &item.Raw, &item.Note, &item.CreatedBy, &item.CreatedAt)
	if errors.Is(err, sql.ErrNoRows) {
		return LegacyJsonRevision{}, errors.New("revision not found")
	}
	return item, err
}
