package models

import (
	"database/sql"
	"errors"

	"mengpost-backend/database"
)

// ErrOAuthPendingNotFound state 不存在或尚未完成微软回调.
var ErrOAuthPendingNotFound = errors.New("oauth state 无效或已过期")

func InsertOAuthPendingState(state string) error {
	_, err := database.DB.Exec(`INSERT INTO oauth_microsoft_pending(state) VALUES(?)`, state)
	return err
}

func UpdateOAuthPendingTokens(state, refresh, email string) error {
	res, err := database.DB.Exec(
		`UPDATE oauth_microsoft_pending SET refresh_token=?, email=? WHERE state=?`,
		refresh, email, state,
	)
	if err != nil {
		return err
	}
	n, _ := res.RowsAffected()
	if n == 0 {
		return ErrOAuthPendingNotFound
	}
	return nil
}

// TakeOAuthPending 取出并删除 pending，用于完成账户创建.
func TakeOAuthPending(state string) (refresh, email string, err error) {
	row := database.DB.QueryRow(
		`SELECT refresh_token, email FROM oauth_microsoft_pending WHERE state=? AND refresh_token IS NOT NULL AND email IS NOT NULL`,
		state,
	)
	if err := row.Scan(&refresh, &email); err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return "", "", ErrOAuthPendingNotFound
		}
		return "", "", err
	}
	_, _ = database.DB.Exec(`DELETE FROM oauth_microsoft_pending WHERE state=?`, state)
	return refresh, email, nil
}
