package client

import (
	"fmt"
	"net/http"
	"time"

	"git.sr.ht/~ashkeel/strimertul/twitch/chat"

	"git.sr.ht/~ashkeel/strimertul/twitch"

	"github.com/nicklaw5/helix/v2"
)

func (c *Client) GetLoggedUser() (helix.User, error) {
	if c.User.ID != "" {
		return c.User, nil
	}

	client, err := twitch.GetUserClient(c.DB, twitch.AuthKey, false)
	if err != nil {
		return helix.User{}, fmt.Errorf("failed getting API client for user: %w", err)
	}

	users, err := client.GetUsers(&helix.UsersParams{})
	if err != nil {
		return helix.User{}, fmt.Errorf("failed looking up user: %w", err)
	}
	if len(users.Data.Users) < 1 {
		return helix.User{}, fmt.Errorf("no users found")
	}
	c.User = users.Data.Users[0]

	return c.User, nil
}

func (c *Client) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Get code from params
	code := req.URL.Query().Get("code")
	if code == "" {
		// TODO Nice error page
		http.Error(w, "missing code", http.StatusBadRequest)
		return
	}

	// Exchange code for access/refresh tokens
	userTokenResponse, err := c.API.RequestUserAccessToken(code)
	if err != nil {
		http.Error(w, "failed auth token request: "+err.Error(), http.StatusInternalServerError)
		return
	}

	// Check scope to see which credentials are we getting (stream/chat)
	state := req.URL.Query().Get("state")
	key := twitch.AuthKey
	switch state {
	case "chat":
		key = chat.CustomAccountKey
	}

	err = c.DB.PutJSON(key, twitch.AuthResponse{
		AccessToken:  userTokenResponse.Data.AccessToken,
		RefreshToken: userTokenResponse.Data.RefreshToken,
		ExpiresIn:    userTokenResponse.Data.ExpiresIn,
		Scope:        userTokenResponse.Data.Scopes,
		Time:         time.Now(),
	})
	if err != nil {
		http.Error(w, "error saving auth data for user: "+err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Add("Content-Type", "text/html")
	_, _ = fmt.Fprintf(w, `<html><body><h2>All done, you can close me now!</h2><script>window.close();</script></body></html>`)
}

type RefreshResponse struct {
	AccessToken  string   `json:"access_token"`
	RefreshToken string   `json:"refresh_token"`
	TokenType    string   `json:"token_type"`
	Scope        []string `json:"scope"`
}
