// Package repositories provides data access logic backed by PostgreSQL via pgxpool.
package repositories

import (
	"context"

	"github.com/CubeCraft-Creations/Extrudex/backend/internal/models"
	"github.com/jackc/pgx/v5/pgxpool"
)

// MaterialRepository handles database queries for material lookup tables.
type MaterialRepository struct {
	pool *pgxpool.Pool
}

// NewMaterialRepository creates a MaterialRepository backed by the given pool.
func NewMaterialRepository(pool *pgxpool.Pool) *MaterialRepository {
	return &MaterialRepository{pool: pool}
}

// GetAll returns all material bases ordered by name.
func (r *MaterialRepository) GetAll(ctx context.Context) ([]models.MaterialBase, error) {
	rows, err := r.pool.Query(ctx, `
		SELECT id, name, density_g_cm3, extrusion_temp_min, extrusion_temp_max,
		       bed_temp_min, bed_temp_max, created_at, updated_at
		FROM material_bases
		ORDER BY name
	`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var materials []models.MaterialBase
	for rows.Next() {
		var m models.MaterialBase
		if err := rows.Scan(
			&m.ID, &m.Name, &m.DensityGCm3,
			&m.ExtrusionTempMin, &m.ExtrusionTempMax,
			&m.BedTempMin, &m.BedTempMax,
			&m.CreatedAt, &m.UpdatedAt,
		); err != nil {
			return nil, err
		}
		materials = append(materials, m)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	if materials == nil {
		materials = []models.MaterialBase{}
	}
	return materials, nil
}
