package com.writeoff.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class JwtTokenService {
    private final Key key;
    private final long accessExpireMs;

    public JwtTokenService(@Value("${app.security.jwt-secret}") String secret,
                           @Value("${app.security.access-expire-minutes:${app.security.jwt-expire-minutes:120}}") long accessExpireMinutes) {
        byte[] bytes = secret.getBytes(StandardCharsets.UTF_8);
        if (bytes.length < 32) {
            byte[] padded = new byte[32];
            System.arraycopy(bytes, 0, padded, 0, bytes.length);
            bytes = padded;
        }
        this.key = Keys.hmacShaKeyFor(bytes);
        this.accessExpireMs = accessExpireMinutes * 60 * 1000;
    }

    public String createTenantToken(Long userId, Long tenantId, String phone) {
        return createTenantToken(userId, tenantId, phone, null);
    }

    public String createTenantToken(Long userId, Long tenantId, String phone, Long sessionId) {
        Date now = new Date();
        Date expiry = new Date(now.getTime() + accessExpireMs);
        Map<String, Object> claims = new HashMap<>();
        claims.put("uid", userId);
        claims.put("tid", tenantId);
        claims.put("scope", AuthScope.TENANT.name());
        claims.put("phone", phone);
        if (sessionId != null && sessionId > 0) {
            claims.put("sid", sessionId);
        }
        return Jwts.builder()
                .setClaims(claims)
                .setSubject("writeoff-user")
                .setIssuedAt(now)
                .setExpiration(expiry)
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }

    public String createPlatformToken(Long userId, String phone) {
        return createPlatformToken(userId, phone, null);
    }

    public String createPlatformToken(Long userId, String phone, Long sessionId) {
        Date now = new Date();
        Date expiry = new Date(now.getTime() + accessExpireMs);
        Map<String, Object> claims = new HashMap<>();
        claims.put("uid", userId);
        claims.put("scope", AuthScope.PLATFORM.name());
        claims.put("phone", phone);
        if (sessionId != null && sessionId > 0) {
            claims.put("sid", sessionId);
        }
        return Jwts.builder()
                .setClaims(claims)
                .setSubject("writeoff-user")
                .setIssuedAt(now)
                .setExpiration(expiry)
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }

    public Claims parse(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}
