package expense

import (
	"database/sql"

	"gitea.frenchtouch.duckdns.org/kratisto/budget-backend/internal/storage/dao/postgresql"
	"gitea.frenchtouch.duckdns.org/kratisto/budget-backend/internal/utils"

	"github.com/lib/pq"
)

type Database struct {
	*postgresql.DatabasePostgreSQL
}

func (db *Database) CreateExpense(expense *Expense) error {
	q := `
		INSERT INTO public.expense
			(account_id, value, type_expense, expense_date, libelle)
		VALUES
			($1, $2, $3, $4, $5)
		RETURNING id, created_at
	`

	err := db.Session.
		QueryRow(q, expense.AccountId, expense.Value, expense.TypeExpense, expense.ExpenseDate, expense.Libelle).
		Scan(&expense.ID, &expense.CreatedAt)
	if err != nil {
		utils.GetLogger().Info(err)
	}
	if errPq, ok := err.(*pq.Error); ok {
		return postgresql.HandlePgError(errPq)
	}
	return err
}

func (db Database) GetExpensesOfAnAccountBetween(id, from, to string) ([]*Expense, error) {
	q := `
		SELECT a.id, a.account_id, a.value, a.type_expense, a.expense_date, a.created_at, a.updated_at, a.libelle
		FROM public.expense a
		WHERE a.account_id = $1
		AND a.expense_date BETWEEN $2 and $3
	`
	rows, err := db.Session.Query(q, id, from, to)
	if err != nil {
		return nil, err
	}
	defer func(rows *sql.Rows) {
		err := rows.Close()
		if err != nil {
			return
		}
	}(rows)

	es := make([]*Expense, 0)
	for rows.Next() {
		e := Expense{}
		err := rows.Scan(&e.ID, &e.AccountId, &e.Value, &e.TypeExpense, &e.ExpenseDate, &e.CreatedAt, &e.UpdatedAt, &e.Libelle)
		if err != nil {
			return nil, err
		}
		es = append(es, &e)
	}
	return es, nil
}

func (db Database) GetAllExpensesOfAnAccount(id string) ([]*Expense, error) {
	q := `
		SELECT a.id, a.account_id, a.value, a.type_expense, a.expense_date, a.created_at, a.updated_at, a.libelle
		FROM public.expense a
		WHERE a.account_id = $1
	`
	rows, err := db.Session.Query(q, id)
	if err != nil {
		return nil, err
	}
	defer func(rows *sql.Rows) {
		err := rows.Close()
		if err != nil {
			return
		}
	}(rows)

	es := make([]*Expense, 0)
	for rows.Next() {
		e := Expense{}
		err := rows.Scan(&e.ID, &e.AccountId, &e.Value, &e.TypeExpense, &e.ExpenseDate, &e.CreatedAt, &e.UpdatedAt, &e.Libelle)
		if err != nil {
			return nil, err
		}
		es = append(es, &e)
	}
	return es, nil
}

func NewDatabase(db *postgresql.DatabasePostgreSQL) *Database {
	return &Database{db}
}
