package storage

import (
    "database/sql"
    "time"
)

type ConfigVersionRecord struct {
    ID         int    `json:"id"`
    DeviceID   string `json:"device_id"`
    ConfigID   string `json:"config_id"`
    ConfigJSON string `json:"config_json"`
    CreatedAt  string `json:"created_at"`
}

type ConfigVersionsRepo struct {
    db *sql.DB
}

func NewConfigVersionsRepo(db *sql.DB) *ConfigVersionsRepo {
    return &ConfigVersionsRepo{db: db}
}

func (r *ConfigVersionsRepo) Save(deviceID, configID, configJSON string) error {
    if r == nil || r.db == nil {
        return nil
    }
    _, err := r.db.Exec(`INSERT INTO config_versions(device_id, config_id, config_json, created_at) VALUES(?,?,?,?)`,
        deviceID, configID, configJSON, time.Now().Format(time.RFC3339))
    return err
}

func (r *ConfigVersionsRepo) List(deviceID string) ([]ConfigVersionRecord, error) {
    if r == nil || r.db == nil {
        return nil, nil
    }
    rows, err := r.db.Query(`SELECT id, device_id, config_id, config_json, created_at FROM config_versions WHERE device_id=? ORDER BY id DESC LIMIT 20`, deviceID)
    if err != nil {
        return nil, err
    }
    defer rows.Close()
    var results []ConfigVersionRecord
    for rows.Next() {
        var rec ConfigVersionRecord
        if err := rows.Scan(&rec.ID, &rec.DeviceID, &rec.ConfigID, &rec.ConfigJSON, &rec.CreatedAt); err != nil {
            continue
        }
        results = append(results, rec)
    }
    return results, rows.Err()
}

func (r *ConfigVersionsRepo) GetByID(id int) (*ConfigVersionRecord, error) {
    if r == nil || r.db == nil {
        return nil, nil
    }
    var rec ConfigVersionRecord
    err := r.db.QueryRow(`SELECT id, device_id, config_id, config_json, created_at FROM config_versions WHERE id=?`, id).Scan(&rec.ID, &rec.DeviceID, &rec.ConfigID, &rec.ConfigJSON, &rec.CreatedAt)
    if err != nil {
        return nil, err
    }
    return &rec, nil
}
