package postgresql

import (
	"context"
	"fmt"

	"gitea.computernetthings.ru/yash/crypto_alert_bot/internal/entities"
)

const instrumentListQuery = `
select i.id, c_base.symbol, c_quote.symbol
from instrument i
join currency c_base on c_base.id = i.base_currency_id
join currency c_quote on c_quote.id = i.quoted_currency_id
order by i.id
offset $1 limit $2`

func (p *Postgresql) InstrumentList(ctx context.Context, offset, limit int) ([]entities.Instrument, error) {
	rows, err := p.db.Query(ctx, instrumentListQuery, offset, limit)
	if err != nil {
		return nil, fmt.Errorf("failed to exec instrumentListQuery: %w", err)
	}
	defer rows.Close()

	var instruments []entities.Instrument
	for rows.Next() {
		var inst entities.Instrument
		if err := rows.Scan(&inst.ID, &inst.BaseCurrency, &inst.QuoteCurrency); err != nil {
			return nil, fmt.Errorf("failed to scan instrument row: %w", err)
		}
		instruments = append(instruments, inst)
	}

	return instruments, nil
}

const createInstrumentQuery = `
insert into instrument(base_currency_id, quoted_currency_id)
values (
  (select id from currency where symbol = $1),
  (select id from currency where symbol = $2)
)
returning id`

func (p *Postgresql) CreateInstrument(ctx context.Context, instrument *entities.Instrument) (entities.InstrumentID, error) {
	var id entities.InstrumentID

	err := p.db.QueryRow(ctx, createInstrumentQuery, instrument.BaseCurrency, instrument.QuoteCurrency).Scan(&id)
	if err != nil {
		return "", fmt.Errorf("failed to exec createInstrumentQuery: %w", err)
	}

	return id, nil
}
