package com.honey.honey.service;

import com.honey.honey.model.Admin;
import com.honey.honey.repository.AdminRepository;
import com.honey.honey.security.admin.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class AdminService {

    private final AdminRepository adminRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    public Optional<String> authenticate(String username, String password) {
        Optional<Admin> adminOpt = adminRepository.findByUsername(username);
        
        if (adminOpt.isEmpty()) {
            return Optional.empty();
        }

        Admin admin = adminOpt.get();

        // Check password
        if (!passwordEncoder.matches(password, admin.getPasswordHash())) {
            return Optional.empty();
        }

        // Generate JWT token
        String token = jwtUtil.generateToken(admin.getId(), username);
        return Optional.of(token);
    }

    public Optional<Admin> getAdminByUsername(String username) {
        return adminRepository.findByUsername(username);
    }
}

