package repositories

import (
	"context"
	"database/sql"

	"gitea.d3m0k1d.ru/d3m0k1d/d3m0k1d.ru/backend/internal/logger"

	"gitea.d3m0k1d.ru/d3m0k1d/d3m0k1d.ru/backend/internal/storage"
)

type commentsRepository struct {
	db     *sql.DB
	logger *logger.Logger
}

func NewCommentsRepository(db *sql.DB) CommentRepository {
	return &commentsRepository{
		db:     db,
		logger: logger.New(false),
	}
}

func (c *commentsRepository) CreateComment(
	ctx context.Context,
	comment *storage.CommentCreate,
) error {
	_, err := c.db.Exec(
		"INSERT INTO comments(content, post_id) VALUES(?, ?, ?)",
		comment.Content,
		comment.PostID,
		comment.UserID,
	)
	if err != nil {
		c.logger.Error("error insert: " + err.Error())
		return err
	}
	return nil
}

func (c *commentsRepository) GetAllComments(ctx context.Context) ([]storage.Comment, error) {
	var result []storage.Comment
	rows, err := c.db.Query("SELECT id, content, post_id, user_id, created_at FROM comments")
	if err != nil {
		c.logger.Error("error scan " + err.Error())
		return nil, err
	}
	for rows.Next() {
		var id int
		var content string
		var postID int
		var userID int
		var createdAt string
		err := rows.Scan(&id, &content, &postID, &userID, &createdAt)
		if err != nil {
			c.logger.Error("error scan: " + err.Error())
		}
		result = append(result, storage.Comment{
			ID:        id,
			Content:   content,
			PostID:    postID,
			UserID:    userID,
			CreatedAt: createdAt,
		})
	}
	return result, nil
}

func (c *commentsRepository) GetCommentsOfPost(
	ctx context.Context,
	id int,
) ([]storage.Comment, error) {
	return nil, nil
}

func (c *commentsRepository) DeleteComment(ctx context.Context, id int) error {
	return nil
}

func (c *commentsRepository) UpdateComment(
	ctx context.Context,
	id int,
	comment *storage.Comment,
) error {
	return nil
}
