package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.service.ILicenseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/license")
public class LicenseController {

    @Autowired
    private ILicenseService licenseService;

    @PostMapping("/activate")
    public AjaxResult activateLicense(@RequestParam String licenseKey,
                                      @RequestParam String expireDate) {
        Date expire = DateUtils.parseDate(expireDate);
        boolean success = licenseService.activateLicense(licenseKey, expire);
        return success ? AjaxResult.success("授权激活成功")
                : AjaxResult.error("授权密钥无效");
    }

    @PostMapping("/getLicenseKey")
    public AjaxResult getLicenseKey(String expire) {
        Date expireDate = DateUtils.parseDate(expire);
        String licenseKey = licenseService.generateLicenseKey(expireDate);
        return  AjaxResult.success(licenseKey);
    }

    @GetMapping("/check")
    public AjaxResult checkLicense() {
        boolean isValid = licenseService.checkLicense();
        Date expireDate = licenseService.getExpireDate();
        return AjaxResult.success("检查成功", new LicenseStatus(isValid, expireDate));
    }

    static class LicenseStatus {
        private boolean valid;
        private Date expireDate;
        private boolean expired;

        public LicenseStatus(boolean valid, Date expireDate) {
            this.valid = valid;
            this.expireDate = expireDate;
            this.expired = expireDate != null && expireDate.before(new Date());
        }

        // getters and setters
    }
}
