package db

import (
	"encoding/json"
	"time"

	"crypto-miner-server/internal/models"
)

func (d *Database) InsertAudit(username, action, agentID string, detail interface{}) error {
	var detailJSON []byte
	if detail != nil {
		var err error
		detailJSON, err = json.Marshal(detail)
		if err != nil {
			detailJSON = []byte("{}")
		}
	}
	_, err := d.Exec(
		`INSERT INTO audit_log (timestamp, username, action, agent_id, detail) VALUES (?, ?, ?, ?, ?)`,
		time.Now(), username, action, agentID, string(detailJSON),
	)
	return err
}

func (d *Database) ListAudit(limit int) ([]*models.AuditEntry, error) {
	if limit <= 0 {
		limit = 50
	}
	if limit > 500 {
		limit = 500
	}
	rows, err := d.Query(
		`SELECT id, timestamp, username, action, agent_id, detail FROM audit_log ORDER BY id DESC LIMIT ?`,
		limit,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var out []*models.AuditEntry
	for rows.Next() {
		e := &models.AuditEntry{}
		var detailStr string
		if err := rows.Scan(&e.ID, &e.Timestamp, &e.Username, &e.Action, &e.AgentID, &detailStr); err != nil {
			return nil, err
		}
		if detailStr != "" {
			e.Detail = json.RawMessage(detailStr)
		}
		out = append(out, e)
	}
	return out, nil
}
