package com.honey.honey.controller;

import com.honey.honey.dto.CreateSessionRequest;
import com.honey.honey.dto.CreateSessionResponse;
import com.honey.honey.exception.BannedUserException;
import com.honey.honey.model.UserA;
import com.honey.honey.service.LocalizationService;
import com.honey.honey.service.SessionService;
import com.honey.honey.service.TelegramAuthService;
import com.honey.honey.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final TelegramAuthService telegramAuthService;
    private final SessionService sessionService;
    private final UserService userService;
    private final LocalizationService localizationService;

    /**
     * Creates a session by validating Telegram initData.
     * This is the only endpoint that accepts initData.
     * Handles user registration/login and referral system.
     */
    @PostMapping("/tma/session")
    public CreateSessionResponse createSession(
            @RequestBody CreateSessionRequest request,
            HttpServletRequest httpRequest) {
        String initData = request.getInitData();

        if (initData == null || initData.isBlank()) {
            throw new IllegalArgumentException(localizationService.getMessage("auth.error.initDataRequired"));
        }

        // Validate Telegram initData signature and parse data
        Map<String, Object> tgUserData = telegramAuthService.validateAndParseInitData(initData);

        // Get or create user (handles registration, login update, and referral system)
        // Note: Referral handling is done via bot registration endpoint, not through WebApp initData
        UserA user = userService.getOrCreateUser(tgUserData, httpRequest);

        if (user.getBanned() != null && user.getBanned() == 1) {
            String message = localizationService.getMessageForUser(user.getId(), "auth.error.accessRestricted");
            throw new BannedUserException(message);
        }

        // Create session
        String sessionId = sessionService.createSession(user);

        log.debug("Session created: userId={}", user.getId());

        return CreateSessionResponse.builder()
                .access_token(sessionId)
                .expires_in(sessionService.getSessionTtlSeconds())
                .build();
    }

    /**
     * Logs out by invalidating the session.
     * This endpoint requires authentication (Bearer token).
     */
    @PostMapping("/logout")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void logout(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        if (authHeader == null) {
            log.warn("Logout called without Authorization header");
            return;
        }
        
        String sessionId = extractBearerToken(authHeader);
        if (sessionId != null) {
            sessionService.invalidateSession(sessionId);
            log.debug("Session invalidated via logout");
        }
    }

    /**
     * Extracts Bearer token from Authorization header.
     */
    private String extractBearerToken(String authHeader) {
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }
}

