package main

import (
	"fmt"
	"time"

	"fn-registry/functions/infra"
)

// persistCopiedCode runs infra.AuditCopiedCode and INSERT OR IGNOREs results
// into the copied_code table. Returns (newly_inserted, total_detected, error).
func persistCopiedCode(callDB *DB, registryRoot string) (int, int, error) {
	entries, err := infra.AuditCopiedCode(registryRoot)
	if err != nil {
		return 0, 0, fmt.Errorf("audit: %w", err)
	}
	now := time.Now().UTC().Unix()
	tx, err := callDB.conn.Begin()
	if err != nil {
		return 0, 0, err
	}
	stmt, err := tx.Prepare(`INSERT OR IGNORE INTO copied_code
		(app_file, app_function, registry_id, body_hash, similarity, kind, detected_at)
		VALUES (?, ?, ?, ?, ?, ?, ?)`)
	if err != nil {
		_ = tx.Rollback()
		return 0, 0, err
	}
	defer stmt.Close()
	inserted := 0
	for _, e := range entries {
		res, err := stmt.Exec(e.AppFile, e.AppFunction, e.RegistryID, e.BodyHash, e.Similarity, e.Kind, now)
		if err != nil {
			_ = tx.Rollback()
			return 0, 0, err
		}
		if n, _ := res.RowsAffected(); n > 0 {
			inserted++
		}
	}
	if err := tx.Commit(); err != nil {
		return 0, 0, err
	}
	return inserted, len(entries), nil
}
