package controllers

import (
	"canguidev/shelfy/internal/client"
	"context"
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func PostDebridLogin(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		clt := client.NewClient(db)

		var creds struct {
			Username string `json:"username"`
			Password string `json:"password"`
		}
		if err := c.ShouldBindJSON(&creds); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})
			return
		}

		deviceResp, err := clt.RequestDeviceCodeWithCredentials(c, creds.Username, creds.Password)
		if err != nil {
			log.Println("[OAuth2] Erreur device_code:", err)
			c.JSON(http.StatusInternalServerError, gin.H{"error": "OAuth error: " + err.Error()})
			return
		}

		go func() {
			tokens, err := clt.PollDeviceToken(context.Background(), deviceResp.DeviceCode, deviceResp.Interval)
			if err != nil {
				log.Println("[OAuth2] Polling échoué:", err)
				return
			}

			account := &client.DebridAccount{
				Host:         "debrid-link.com",
				Username:     creds.Username,
				Password:     creds.Password,
				IsActive:     true,
				AccessToken:  tokens.AccessToken,
				RefreshToken: tokens.RefreshToken,
				ExpiresAt:    time.Now().Add(time.Duration(tokens.ExpiresIn) * time.Second),
			}

			if err := db.Create(account).Error; err != nil {
				log.Println("[DB] Sauvegarde échouée:", err)
				return
			}
			log.Println("[OAuth2] Compte sauvegardé")
		}()

		c.JSON(http.StatusOK, gin.H{
			"message":       "Device code retrieved successfully",
			"user_code":     deviceResp.UserCode,
			"verify_url":    deviceResp.VerificationURL,
			"polling_delay": deviceResp.Interval,
		})
	}
}
func GetDebridAccounts(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		clt := client.NewClient(db)
		accounts, err := clt.ListDebridAccounts(c)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to list accounts"})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"accounts": accounts,
		})
	}
}
func GetDebridStatus(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		username := c.Query("username")
		var account client.DebridAccount
		if err := db.Where("username = ? AND is_active = ?", username, true).First(&account).Error; err != nil {
			c.JSON(http.StatusOK, gin.H{"active": false})
			return
		}
		c.JSON(http.StatusOK, gin.H{"active": true})
	}
}
