package storage

import (
	"errors"
	"git.sch9.ru/new_gate/ms-tester/internal/lib"
	"github.com/jackc/pgerrcode"
	"github.com/jackc/pgx/v5/pgconn"
)

func handlePgErr(err error) error {
	var pgErr *pgconn.PgError
	if !errors.As(err, &pgErr) {
		return lib.StorageError(err, lib.ErrUnknown, "unexpected error from postgres")
	}
	if pgerrcode.IsIntegrityConstraintViolation(pgErr.Code) {
		// TODO: probably should specify which constraint
		return lib.StorageError(err, lib.ErrConflict, pgErr.Message)
	}
	if pgerrcode.IsNoData(pgErr.Code) {
		return lib.StorageError(err, lib.ErrNotFound, pgErr.Message)
	}
	return lib.StorageError(err, lib.ErrUnimplemented, "unimplemented error")
}
