package db

import (
	"context"
	"database/sql"
	"log/slog"

	"git.maximotejeda.com/maximo/tgb-user/internal/application/core/domain"
)

type BotUser struct {
	db      *sql.DB
	log     *slog.Logger
	ID      int64 `json:"id"`
	Tgb_ID  int64 `json:"tgb_id"`
	Bot_id  int64 `json:"bot_id"`
	Created int64 `json:"edited"`
}

func NewBotUser(db *sql.DB, log *slog.Logger) *BotUser {
	log = log.With("obj", "BotUsers")
	return &BotUser{
		db:  db,
		log: log,
	}
}

func (bu BotUser) GetUsers(ctx context.Context, botName string) (ul []*domain.User, err error) {
	smt, err := bu.db.PrepareContext(ctx,
		`SELECT u.tgb_id, u.username, u.first_name, u.last_name, u.created, u.edited
                    FROM bot_users AS bu
                 JOIN bots as b ON b.id = bu.bot_id
                 JOIN users as u ON bu.tgb_id = u.tgb_id
               WHERE b.bot_name = ? AND u.deleted IS NULL;`)
	if err != nil {
		bu.log.Error("prepare stmt getUsers", "error", err)
		return nil, err
	}
	defer smt.Close()
	rows, err := smt.QueryContext(ctx, botName)
	if err != nil {
		bu.log.Error("query  getUsers", "error", err)
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		u := &domain.User{}
		err = rows.Scan(&u.TGB_ID, &u.Username, &u.FirstName, &u.LastName, &u.Created, &u.Edited)
		if err != nil {
			bu.log.Error("canning getUsers", "error", err)
			return nil, err
		}
		ul = append(ul, u)
	}
	return ul, nil
}

func (bu BotUser) GetBots(ctx context.Context, tgb_id int64) (bl []*domain.Bot, err error) {
	stmt, err := bu.db.PrepareContext(ctx,
		`SELECT b.id, b.bot_name, b.created FROM bot_users AS bu
                  JOIN bots AS b ON bu.bot_id = b.id
                     WHERE bu.tgb_id = ?;`)
	if err != nil {
		bu.log.Error("prepare stmt getBots", "error", err)
		return nil, err
	}
	defer stmt.Close()
	rows, err := stmt.QueryContext(ctx, tgb_id)
	if err != nil {
		bu.log.Error("query get bots", "error", err)
		return nil, err
	}
	defer rows.Close()
	bl = []*domain.Bot{}
	for rows.Next() {
		bot := &domain.Bot{}
		err := rows.Scan(&bot.ID, &bot.BotName, &bot.Created)
		if err != nil {
			bu.log.Error("scanning get bots", "error", err)
			return nil, err
		}
		bl = append(bl, bot)

	}
	return bl, nil
}

func (bu BotUser) CreateBot(ctx context.Context, bot_name string) (bool, error) {
	stmt, err := bu.db.PrepareContext(ctx,
		`INSERT OR IGNORE INTO bots (bot_name, created) VALUES(?, strftime('%s', 'now'));`)
	if err != nil {
		bu.log.Error("prepare stmt add", "error", err)
		return false, err
	}
	defer stmt.Close()
	_, err = stmt.ExecContext(ctx, bot_name)

	if err != nil {
		bu.log.Error("exec context add", "error", err)
		return false, err
	}
	return true, nil

}

func (bu BotUser) Add(ctx context.Context, tgb_id int64, bot_name string) (bool, error) {

	stmt1, err := bu.db.PrepareContext(ctx,
		`
INSERT INTO bot_users
    (tgb_id, bot_id, created)
VALUES(?,(SELECT id FROM bots WHERE bot_name = ?),strftime('%s', 'now'));`)

	if err != nil {
		bu.log.Error("prepare stmt add botusers", "error", err)
		return false, err
	}
	defer stmt1.Close()
	_, err = stmt1.ExecContext(ctx, tgb_id, bot_name)
	if err != nil {
		bu.log.Error("exec add bot users", "error", err)
		return false, err
	}
	return true, nil
}

func (bu BotUser) Delete(ctx context.Context, tgb_id int64, botname string) (bool, error) {
	stmt, err := bu.db.PrepareContext(ctx,
		`
DELETE FROM bot_users as u
WHERE u.bot_id = (SELECT id FROM bots WHERE bot_name = ?) AND u.tgb_id = ?
`)
	if err != nil {
		bu.log.Error("prepare stmt delete", "error", err)
		return false, err
	}
	defer stmt.Close()
	_, err = stmt.ExecContext(ctx, botname, tgb_id)
	if err != nil {
		bu.log.Error("exec delete", "error", err)
		return false, err
	}
	return true, nil
}

func (bu BotUser) GetAllBots(ctx context.Context) ([]*domain.Bot, error) {
	stmt, err := bu.db.Prepare(`SELECT id, bot_name, created FROM bots`)
	if err != nil {
		bu.log.Error("prepare stmt get all bots", "error", err)
		return nil, err
	}
	stmt.Close()
	rows, err := stmt.Query()
	if err != nil {
		bu.log.Error("query get all bots", "error", err)
		return nil, err
	}
	defer rows.Close()
	list := []*domain.Bot{}
	for rows.Next() {
		bot := &domain.Bot{}
		err := rows.Scan(&bot.ID, &bot.BotName, &bot.Created)
		if err != nil {
			bu.log.Error("scanning get all bots", "error", err)
			continue
		}
		list = append(list, bot)
	}
	return list, nil
}
