package storage

import (
    "database/sql"
    "time"
)

type StandardModelRecord struct {
    Name        string
    FileName    string
    Version     string
    SHA256      string
    SizeBytes   int64
    ModelType   string
    Description string
    CreatedAt   string
    UpdatedAt   string
}

type ModelsRepo struct {
    db *sql.DB
}

func NewModelsRepo(db *sql.DB) *ModelsRepo {
    return &ModelsRepo{db: db}
}

func (r *ModelsRepo) Save(item StandardModelRecord) error {
    if r == nil || r.db == nil {
        return nil
    }
    now := time.Now().Format(time.RFC3339)
    createdAt := item.CreatedAt
    if createdAt == "" {
        createdAt = now
    }
    updatedAt := item.UpdatedAt
    if updatedAt == "" {
        updatedAt = now
    }
    _, err := r.db.Exec(`
INSERT INTO standard_models(name, file_name, version, sha256, size_bytes, model_type, description, created_at, updated_at)
VALUES(?, ?, ?, ?, ?, ?, ?, COALESCE((SELECT created_at FROM standard_models WHERE name = ?), ?), ?)
ON CONFLICT(name) DO UPDATE SET
  file_name=excluded.file_name,
  version=excluded.version,
  sha256=excluded.sha256,
  size_bytes=excluded.size_bytes,
  model_type=excluded.model_type,
  description=excluded.description,
  updated_at=excluded.updated_at
`, item.Name, item.FileName, item.Version, item.SHA256, item.SizeBytes, item.ModelType, item.Description, item.Name, createdAt, updatedAt)
    return err
}

func (r *ModelsRepo) List() ([]StandardModelRecord, error) {
    if r == nil || r.db == nil {
        return nil, nil
    }
    rows, err := r.db.Query(`
SELECT name, file_name, version, sha256, size_bytes, model_type, description, created_at, updated_at
FROM standard_models
ORDER BY name ASC
`)
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    out := make([]StandardModelRecord, 0)
    for rows.Next() {
        var item StandardModelRecord
        if err := rows.Scan(
            &item.Name,
            &item.FileName,
            &item.Version,
            &item.SHA256,
            &item.SizeBytes,
            &item.ModelType,
            &item.Description,
            &item.CreatedAt,
            &item.UpdatedAt,
        ); err != nil {
            return nil, err
        }
        out = append(out, item)
    }
    return out, rows.Err()
}
