package repo

import (
	"58team_blog/internal/domain/entities"
	"58team_blog/internal/infrastructure/db"

	"github.com/google/uuid"
	"github.com/jmoiron/sqlx"
)

type ImagesRepository struct {
	conn *db.Database
}

func CreateImagesRepository(conn *db.Database) ImagesRepository {
	return ImagesRepository{
		conn: conn,
	}
}

func (r *ImagesRepository) Create(entity *entities.Images) error {
	query := "INSERT INTO " + entities.ImagesTable + "(id, path) VALUES (:id, :path)"
	_, err := r.conn.Conn.NamedExec(query, entity)

	return err
}

func (r *ImagesRepository) FindById(id uuid.UUID) (*entities.Images, error) {
	var entity *entities.Images

	query := "SELECT * FROM " + entities.ImagesTable + " WHERE id = ?"
	query, args, err := sqlx.In(query, id)
	if err != nil {
		return nil, err
	}

	query = r.conn.Conn.Rebind(query)
	err = r.conn.Conn.Get(entity, query, args...)
	if err != nil {
		return nil, err
	}

	return entity, nil
}

func (r *ImagesRepository) Delete(id uuid.UUID) error {
	query := "DELETE FROM " + entities.ImagesTable + " WHERE id=?"

	query, args, err := sqlx.In(query, id)
	if err != nil {
		return err
	}

	query = r.conn.Conn.Rebind(query)
	_, err = r.conn.Conn.Query(query, args...)

	return err
}
