package storage

import (
	"database/sql"
	"time"
)

type AuditLogRecord struct {
	ID          int64
	Actor       string
	Action      string
	TargetType  string
	TargetID    string
	DetailsJSON string
	CreatedAt   string
}

type AuditLogsRepo struct {
	db *sql.DB
}

func NewAuditLogsRepo(db *sql.DB) *AuditLogsRepo {
	return &AuditLogsRepo{db: db}
}

func (r *AuditLogsRepo) Append(entry AuditLogRecord) error {
	if r == nil || r.db == nil {
		return nil
	}
	actor := entry.Actor
	if actor == "" {
		actor = "system"
	}
	_, err := r.db.Exec(`
INSERT INTO audit_logs(actor, action, target_type, target_id, details_json, created_at)
VALUES(?, ?, ?, ?, ?, ?)
`, actor, entry.Action, entry.TargetType, entry.TargetID, entry.DetailsJSON, time.Now().Format(time.RFC3339))
	return err
}

func (r *AuditLogsRepo) AppendLog(actor string, action string, targetType string, targetID string, detailsJSON string) error {
	return r.Append(AuditLogRecord{
		Actor:       actor,
		Action:      action,
		TargetType:  targetType,
		TargetID:    targetID,
		DetailsJSON: detailsJSON,
	})
}

func (r *AuditLogsRepo) List() ([]AuditLogRecord, error) {
	if r == nil || r.db == nil {
		return nil, nil
	}
	rows, err := r.db.Query(`
SELECT id, actor, action, target_type, target_id, details_json, created_at
FROM audit_logs
ORDER BY id DESC
`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var out []AuditLogRecord
	for rows.Next() {
		var item AuditLogRecord
		if err := rows.Scan(&item.ID, &item.Actor, &item.Action, &item.TargetType, &item.TargetID, &item.DetailsJSON, &item.CreatedAt); err != nil {
			return nil, err
		}
		out = append(out, item)
	}
	return out, rows.Err()
}
