package repo

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

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

type PostRepository struct {
	conn *db.Database
}

func CreatePostRepository(conn *db.Database) PostRepository {
	return PostRepository{
		conn: conn,
	}
}

func (r *PostRepository) Create(entity *entities.Post) (*entities.Post, error) {
	query := "INSERT INTO " + entities.PostTable + " (id, userid, title, description, content, createdat, updatedat)" +
		"VALUES (:id, :userid, :title, :description, :content, :createdat, :updatedat)"
	_, err := r.conn.Conn.NamedExec(query, entity)

	return entity, err
}

func (r *PostRepository) FindById(id uuid.UUID) (*entities.Post, error) {
	var entity *entities.Post
	query := "SELECT * FROM " + entities.PostTable + " 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)

	return entity, err
}

func (r *PostRepository) FindAllByUserName(userName string) ([]*entities.Post, error) {
	var entity_list []*entities.Post
	query := "SELECT * FROM " + entities.PostTable + " WHERE userid=?"

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

	query = r.conn.Conn.Rebind(query)
	err = r.conn.Conn.Select(entity_list, query, args...)

	return entity_list, err
}

func (r *PostRepository) GetAll() ([]*entities.Post, error) {
	var entity_list []*entities.Post
	query := "SELECT * FROM " + entities.PostTable + " ORDER BY createdat, updatedat LIMIT 5;"

	err := r.conn.Conn.Select(&entity_list, query)

	return entity_list, err
}

func (r *PostRepository) Update(entity *entities.Post) error {
	query := "UPDATE " + entities.PostTable + "SET title=:title, description=:description, content=:content, updatedat=:updatedat WHERE id=:id"

	_, err := r.conn.Conn.NamedExec(query, entity)

	return err
}

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

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

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

	return err
}
