package postgresql

import (
	"database/sql"
	"hamster-tycoon/storage/dao"
	"hamster-tycoon/storage/model"

	"github.com/lib/pq"
)

func (db *DatabasePostgreSQL) GetAllCages() ([]*model.Cage, error) {
	q := `
		SELECT c.id, created_at, updated_at
		FROM public.Cage c
	`
	rows, err := db.session.Query(q)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	cages := make([]*model.Cage, 0)
	for rows.Next() {
		cage := model.Cage{}
		err := rows.Scan(&cage.ID, &cage.CreatedAt, &cage.UpdatedAt)
		if err != nil {
			return nil, err
		}
		cages = append(cages, &cage)
	}
	return cages, nil
}

func (db *DatabasePostgreSQL) GetCageByID(cageID string) (*model.Cage, error) {
	q := `
		SELECT c.id, created_at, updated_at
		FROM public.Cage c
		WHERE c.id = $2 
	`
	row := db.session.QueryRow(q, cageID)

	cage := model.Cage{}
	err := row.Scan(&cage.ID, &cage.CreatedAt, &cage.UpdatedAt)
	if errPq, ok := err.(*pq.Error); ok {
		return nil, handlePgError(errPq)
	}
	if err == sql.ErrNoRows {
		return nil, dao.NewDAOError(dao.ErrTypeNotFound, err)
	}
	return &cage, err
}

func (db *DatabasePostgreSQL) CreateCage(cage *model.Cage) error {
	return nil
}

func (db *DatabasePostgreSQL) DeleteCage(id string) error {
	q := `
		DELETE FROM public.Cage
		WHERE id = $1
	`

	_, err := db.session.Exec(q, id)
	if errPq, ok := err.(*pq.Error); ok {
		return handlePgError(errPq)
	}
	return err
}

func (db *DatabasePostgreSQL) UpdateCage(cage *model.Cage) error {
	return nil
}
