package httpserver

import (
	"context"
	"fmt"
	"strconv"

	_ "github.com/SamuelTariku/FortuneBet-Backend/docs"
	"github.com/SamuelTariku/FortuneBet-Backend/internal/domain"

	// "github.com/SamuelTariku/FortuneBet-Backend/internal/logger/mongoLogger"

	// "github.com/SamuelTariku/FortuneBet-Backend/internal/services/wallet/monitor"

	"github.com/SamuelTariku/FortuneBet-Backend/internal/web_server/handlers"

	"github.com/gofiber/fiber/v2"
	fiberSwagger "github.com/swaggo/fiber-swagger"
)

func (a *App) initAppRoutes() {
	h := handlers.New(
		a.currSvc,
		a.logger,
		a.NotidicationStore,
		a.validator,
		a.reportSvc,
		a.chapaSvc,
		a.walletSvc,
		a.referralSvc,
		a.virtualGameSvc,
		a.aleaVirtualGameService,
		a.veliVirtualGameService,
		a.recommendationSvc,
		a.userSvc,
		a.transactionSvc,
		a.ticketSvc,
		a.betSvc,
		a.authSvc,
		a.JwtConfig,
		a.branchSvc,
		a.companySvc,
		a.prematchSvc,
		a.eventSvc,
		a.leagueSvc,
		*a.resultSvc,
		a.cfg,
	)

	group := a.fiber.Group("/api/v1")

	a.fiber.Get("/", func(c *fiber.Ctx) error {
		return c.JSON(fiber.Map{
			"message": "Welcome to the FortuneBet API",
			"version": "1.0dev3",
		})
	})

	// Auth Routes
	a.fiber.Post("/auth/login", h.LoginCustomer)
	a.fiber.Post("/auth/refresh", h.RefreshToken)
	a.fiber.Post("/auth/logout", a.authMiddleware, h.LogOutCustomer)
	a.fiber.Get("/auth/test", a.authMiddleware, func(c *fiber.Ctx) error {
		userID, ok := c.Locals("user_id").(int64)
		if !ok {
			return fiber.NewError(fiber.StatusUnauthorized, "Invalid user ID")
		}
		role, ok := c.Locals("role").(domain.Role)
		if !ok {
			return fiber.NewError(fiber.StatusUnauthorized, "Invalid role")
		}
		refreshToken, ok := c.Locals("refresh_token").(string)
		if !ok {
			return fiber.NewError(fiber.StatusUnauthorized, "Invalid refresh token")
		}
		companyID, err := strconv.ParseInt(c.Get("company_id"), 10, 64)
		if err != nil {
			return fiber.NewError(fiber.StatusBadRequest, "Invalid company_id")
		}

		a.logger.Info("User ID: " + strconv.FormatInt(userID, 10))
		fmt.Printf("User ID: %d\n", userID)
		a.logger.Info("Role: " + string(role))
		a.logger.Info("Refresh Token: " + refreshToken)
		a.logger.Info("Company ID: " + strconv.FormatInt(companyID, 10))
		return c.SendString("Test endpoint")
	})

	// User Routes
	a.fiber.Post("/user/resetPassword", h.ResetPassword)
	a.fiber.Post("/user/sendResetCode", h.SendResetCode)
	a.fiber.Post("/user/register", h.RegisterUser)
	a.fiber.Post("/user/sendRegisterCode", h.SendRegisterCode)
	a.fiber.Post("/user/checkPhoneEmailExist", h.CheckPhoneEmailExist)
	a.fiber.Get("/user/profile", a.authMiddleware, h.UserProfile)
	a.fiber.Get("/user/single/:id", a.authMiddleware, h.GetUserByID)
	a.fiber.Delete("/user/delete/:id", a.authMiddleware, h.DeleteUser)
	a.fiber.Post("/user/suspend", a.authMiddleware, h.UpdateUserSuspend)
	a.fiber.Get("/user/bets", a.authMiddleware, h.GetBetByUserID)

	a.fiber.Get("/user/wallet", a.authMiddleware, h.GetCustomerWallet)
	a.fiber.Post("/user/search", a.authMiddleware, h.SearchUserByNameOrPhone)

	// Referral Routes
	a.fiber.Post("/referral/create", a.authMiddleware, h.CreateReferralCode)
	a.fiber.Get("/referral/stats", a.authMiddleware, h.GetReferralStats)
	a.fiber.Get("/referral/settings", h.GetReferralSettings)
	a.fiber.Patch("/referral/settings", a.authMiddleware, h.UpdateReferralSettings)

	a.fiber.Get("/cashiers", a.authMiddleware, h.GetAllCashiers)
	a.fiber.Get("/cashiers/:id", a.authMiddleware, h.GetCashierByID)
	a.fiber.Post("/cashiers", a.authMiddleware, h.CreateCashier)
	a.fiber.Put("/cashiers/:id", a.authMiddleware, h.UpdateCashier)

	a.fiber.Get("/admin", a.authMiddleware, h.GetAllAdmins)
	a.fiber.Get("/admin/:id", a.authMiddleware, h.GetAdminByID)
	a.fiber.Post("/admin", a.authMiddleware, h.CreateAdmin)
	a.fiber.Put("/admin/:id", a.authMiddleware, h.UpdateAdmin)

	a.fiber.Get("/managers", a.authMiddleware, h.GetAllManagers)
	a.fiber.Get("/managers/:id", a.authMiddleware, h.GetManagerByID)
	a.fiber.Post("/managers", a.authMiddleware, h.CreateManager)
	a.fiber.Put("/managers/:id", a.authMiddleware, h.UpdateManagers)
	a.fiber.Get("/manager/:id/branch", a.authMiddleware, h.GetBranchByManagerID)

	a.fiber.Get("/odds", h.GetALLPrematchOdds)
	a.fiber.Get("/odds/upcoming/:upcoming_id", h.GetOddsByUpcomingID)
	a.fiber.Get("/odds/upcoming/:upcoming_id/market/:market_id", h.GetRawOddsByMarketID)

	a.fiber.Get("/events", h.GetAllUpcomingEvents)
	a.fiber.Get("/events/:id", h.GetUpcomingEventByID)
	a.fiber.Delete("/events/:id", a.authMiddleware, a.SuperAdminOnly, h.SetEventStatusToRemoved)

	// Leagues
	a.fiber.Get("/leagues", h.GetAllLeagues)
	a.fiber.Put("/leagues/:id/set-active", h.SetLeagueActive)

	a.fiber.Get("/result/:id", h.GetResultsByEventID)

	// Swagger
	a.fiber.Get("/swagger/*", fiberSwagger.FiberWrapHandler())

	// Branch
	a.fiber.Post("/branch", a.authMiddleware, h.CreateBranch)
	a.fiber.Get("/branch", a.authMiddleware, h.GetAllBranches)
	a.fiber.Get("/branch/:id", a.authMiddleware, h.GetBranchByID)
	a.fiber.Get("/branch/:id/bets", a.authMiddleware, h.GetBetByBranchID)
	a.fiber.Put("/branch/:id", a.authMiddleware, h.UpdateBranch)
	a.fiber.Put("/branch/:id/set-active", a.authMiddleware, h.UpdateBranchStatus)
	a.fiber.Put("/branch/:id/set-inactive", a.authMiddleware, h.UpdateBranchStatus)
	a.fiber.Delete("/branch/:id", a.authMiddleware, h.DeleteBranch)
	a.fiber.Get("/search/branch", a.authMiddleware, h.SearchBranch)
	// /branch/search
	// branch/wallet
	a.fiber.Get("/branch/:id/cashiers", a.authMiddleware, h.GetBranchCashiers)
	a.fiber.Get("/branchCashier", a.authMiddleware, h.GetBranchForCashier)

	// Branch Operation
	a.fiber.Get("/supportedOperation", a.authMiddleware, h.GetAllSupportedOperations)
	a.fiber.Post("/supportedOperation", a.authMiddleware, h.CreateSupportedOperation)
	a.fiber.Post("/operation", a.authMiddleware, h.CreateBranchOperation)
	a.fiber.Get("/branch/:id/operation", a.authMiddleware, h.GetBranchOperations)

	a.fiber.Delete("/branch/:id/operation/:opID", a.authMiddleware, h.DeleteBranchOperation)

	// Company
	a.fiber.Post("/company", a.authMiddleware, a.SuperAdminOnly, h.CreateCompany)
	a.fiber.Get("/company", a.authMiddleware, a.SuperAdminOnly, h.GetAllCompanies)
	a.fiber.Get("/company/:id", a.authMiddleware, a.SuperAdminOnly, h.GetCompanyByID)
	a.fiber.Put("/company/:id", a.authMiddleware, a.SuperAdminOnly, h.UpdateCompany)
	a.fiber.Delete("/company/:id", a.authMiddleware, a.SuperAdminOnly, h.DeleteCompany)
	a.fiber.Get("/company/:id/branch", a.authMiddleware, h.GetBranchByCompanyID)
	a.fiber.Get("/search/company", a.authMiddleware, h.SearchCompany)

	// Ticket Routes
	a.fiber.Post("/ticket", h.CreateTicket)
	a.fiber.Get("/ticket", h.GetAllTickets)
	a.fiber.Get("/ticket/:id", h.GetTicketByID)

	// Bet Routes
	a.fiber.Post("/bet", a.authMiddleware, h.CreateBet)
	a.fiber.Get("/bet", a.authMiddleware, h.GetAllBet)
	a.fiber.Get("/bet/:id", h.GetBetByID)
	a.fiber.Get("/bet/cashout/:id", a.authMiddleware, h.GetBetByCashoutID)
	a.fiber.Patch("/bet/:id", a.authMiddleware, h.UpdateCashOut)
	a.fiber.Delete("/bet/:id", a.authMiddleware, h.DeleteBet)

	a.fiber.Post("/random/bet", a.authMiddleware, h.RandomBet)

	// Wallet
	a.fiber.Get("/wallet", h.GetAllWallets)
	a.fiber.Get("/wallet/:id", h.GetWalletByID)
	a.fiber.Put("/wallet/:id", h.UpdateWalletActive)
	a.fiber.Get("/branchWallet", a.authMiddleware, h.GetAllBranchWallets)
	a.fiber.Get("/cashierWallet", a.authMiddleware, h.GetWalletForCashier)

	// Transfer
	// /transfer/wallet - transfer from one wallet to another wallet
	a.fiber.Post("/transfer/wallet/:id", a.authMiddleware, h.TransferToWallet)
	a.fiber.Get("/transfer/wallet/:id", a.authMiddleware, h.GetTransfersByWallet)
	a.fiber.Post("/transfer/refill/:id", a.authMiddleware, h.RefillWallet)

	//Chapa Routes
	group.Post("/chapa/payments/webhook/verify", h.WebhookCallback)
	group.Get("/chapa/payments/manual/verify/:tx_ref", h.ManualVerifyTransaction)
	group.Post("/chapa/payments/deposit", a.authMiddleware, h.InitiateDeposit)
	group.Post("/chapa/payments/withdraw", a.authMiddleware, h.InitiateWithdrawal)
	group.Get("/chapa/banks", h.GetSupportedBanks)

	// Currencies
	group.Get("/currencies", h.GetSupportedCurrencies)
	group.Get("/currencies/convert", h.ConvertCurrency)

	//Report Routes
	group.Get("/reports/dashboard", h.GetDashboardReport)

	//Wallet Monitor Service
	// group.Get("/debug/wallet-monitor/status", func(c *fiber.Ctx) error {
	// 	return c.JSON(fiber.Map{
	// 		"running":    monitor.IsRunning(),
	// 		"last_check": walletMonitorSvc.LastCheckTime(),
	// 	})
	// })

	// group.Post("/debug/wallet-monitor/trigger", func(c *fiber.Ctx) error {
	// 	walletMonitorSvc.ForceCheck()
	// 	return c.SendStatus(fiber.StatusOK)
	// })

	// group.Post("/chapa/payments/initialize", h.InitializePayment)
	// group.Get("/chapa/payments/verify/:tx_ref", h.VerifyTransaction)
	// group.Post("/chapa/payments/callback", h.ReceiveWebhook)
	// group.Get("/chapa/banks", h.GetBanks)
	// group.Post("/chapa/transfers", h.CreateTransfer)
	// group.Get("/chapa/transfers/verify/:transfer_ref", h.VerifyTransfer)

	//Alea Play Virtual Game Routes
	group.Get("/alea-play/launch", a.authMiddleware, h.LaunchAleaGame)
	group.Post("/webhooks/alea-play", a.authMiddleware, h.HandleAleaCallback)

	//Veli Virtual Game Routes
	group.Get("/veli-games/launch", h.LaunchVeliGame)
	group.Post("/webhooks/veli-games", h.HandleVeliCallback)

	//mongoDB logs
	ctx := context.Background()
	group.Get("/logs", a.authMiddleware, a.SuperAdminOnly, handlers.GetLogsHandler(ctx))

	// Recommendation Routes
	group.Get("/virtual-games/recommendations/:userID", h.GetRecommendations)

	// Transactions /transactions
	a.fiber.Post("/transaction", a.authMiddleware, h.CreateTransaction)
	a.fiber.Get("/transaction", a.authMiddleware, h.GetAllTransactions)
	a.fiber.Get("/transaction/:id", a.authMiddleware, h.GetTransactionByID)
	a.fiber.Put("/transaction/:id", a.authMiddleware, h.UpdateTransactionVerified)

	// Notification Routes
	a.fiber.Get("/ws/connect", a.WebsocketAuthMiddleware, h.ConnectSocket)
	a.fiber.Get("/notifications", a.authMiddleware, h.GetNotifications)
	a.fiber.Get("/notifications/all", a.authMiddleware, h.GetAllNotifications)
	a.fiber.Post("/notifications/mark-as-read", a.authMiddleware, h.MarkNotificationAsRead)
	a.fiber.Get("/notifications/unread", a.authMiddleware, h.CountUnreadNotifications)
	a.fiber.Post("/notifications/create", a.authMiddleware, h.CreateAndSendNotification)

	// Virtual Game Routes
	a.fiber.Post("/virtual-game/launch", a.authMiddleware, h.LaunchVirtualGame)
	a.fiber.Post("/virtual-game/callback", h.HandleVirtualGameCallback)
	a.fiber.Post("/playerInfo", h.HandlePlayerInfo)
	a.fiber.Post("/bet", h.HandleBet)
	a.fiber.Post("/win", h.HandleWin)
	a.fiber.Post("/cancel", h.HandleCancel)

}

///user/profile get
// @Router /user/resetPassword [post]
// @Router /user/sendResetCode [post]
// @Router /user/register [post]
// @Router /user/sendRegisterCode [post]
// @Router /user/checkPhoneEmailExist [post]
