package server

import (
	"git.pbiernat.dev/egommerce/identity-service/internal/service"
	"github.com/gofiber/fiber/v2"
)

type AuthLoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

type AuthLoginResponse struct {
	JWTToken string `json:"jwt_token"`
}

func (s *Server) LoginHandler(c *fiber.Ctx) error {
	data := new(AuthLoginRequest)
	if err := c.BodyParser(data); err != nil {
		return err
	}

	token, err := service.AuthService.Login(data.Username, data.Password)
	if err != nil {
		return fiber.NewError(fiber.StatusUnauthorized)
	}

	cookie := service.AuthService.Cookie("auth_token", token)
	c.Cookie(cookie)

	return c.JSON(&AuthLoginResponse{JWTToken: token})
}
