package task

import (
	"git.tek.govt.hu/dowerx/szoe-pontok/database"
	"git.tek.govt.hu/dowerx/szoe-pontok/model"
)

func Add(task model.Task) error {
	db := database.GetDB()

	_, err := db.NamedExec(
		`insert into "task" ("description", "points", "recipient", "issuer") values
		(:description, :points, 
			(select "id" from "user" where "neptun" = :recipient),
			(select "id" from "user" where "neptun" = :issuer)
		)`, task)

	return err
}

func Remove(id int) error {
	db := database.GetDB()

	_, err := db.NamedExec(
		`delete from "task" where "id" = :id`, map[string]interface{}{
			"id": id,
		})

	return err
}

func List(neptun string) ([]model.Task, error) {
	db := database.GetDB()

	rows, err := db.NamedQuery(
		`select "task"."id" as "id","description", "points", "r"."neptun" as "recipient", "i"."neptun" as "issuer", "created_date"
		from "task"
		inner join "user" as "r" on "r"."id" = "task"."recipient"
		inner join "user" as "i" on "i"."id" = "task"."issuer"
		where "r"."neptun" = :neptun`,
		map[string]interface{}{
			"neptun": neptun,
		})

	if err != nil {
		return nil, err
	}

	tasks := []model.Task{}
	var task model.Task

	for rows.Next() {
		err := rows.StructScan(&task)
		if err != nil {
			return nil, err
		}

		tasks = append(tasks, task)
	}

	return tasks, err
}