package dev_services

import (
	"time"

	"cpone/db"
)

func NewServicesLogin(u Login, uStore db.AppStore) *ServicesLogin {

	return &ServicesLogin{
		Login:      u,
		LoginStore: uStore,
	}
}

type Login struct {
	ID        int       `json:"id"`
	Loginname string    `json:"Loginname"`
	Email     string    `json:"Email"`
	Password  string    `json:"Password"`
	CreatedAt time.Time `json:"created_at,omitempty"`
}

type ServicesLogin struct {
	Login      Login
	LoginStore db.AppStore
}

func (su *ServicesLogin) GetLogin(Email string, Password string) (Login, error) {

	query := `SELECT id, Loginname, Email, Password, created_at FROM Login
		WHERE Email = ? AND Password = ?`

	stmt, err := su.LoginStore.Db.Prepare(query)
	if err != nil {
		return Login{}, err
	}

	defer stmt.Close()

	su.Login.Email = Email
	su.Login.Password = Password
	err = stmt.QueryRow(
		su.Login.Email,
		su.Login.Password,
	).Scan(
		&su.Login.ID,
		&su.Login.Loginname,
		&su.Login.Email,
		&su.Login.Password,
		&su.Login.CreatedAt,
	)
	if err != nil {
		return Login{}, err
	}

	return su.Login, nil
}
