
(define-constant total-amount u1000)
(define-data-var last-id uint u0)
(define-map degen-name uint (string-ascii 30))
(define-constant err-bns-convert (err u200))
(define-constant err-bnsx-convert (err u201))
(define-constant err-bns-size (err u202))
(define-constant err-full-mint-reached (err u302))

(define-private (set-nft-name (id uint) (name (string-ascii 30)))
  (map-set degen-name id name))

;; convert to string-ascii version the buff[] of name and namecheap
(define-read-only (get-address-bns-name (bns {name: (buff 20), namespace: (buff 9)}))
  (unwrap-panic (contract-call? .conversions resolve-principal-to-ascii bns)))

;; Internal - Mint new NFT
(define-public (mint (new-owner principal))
  (begin 
    (let 
      ((next-id (+ u1 (var-get last-id)))
        (address-bns-name (contract-call? .bns resolve-principal new-owner))
        (address-bnsx-name (contract-call? .bnsx-fake get-primary-name new-owner))) 
      (asserts! (<= next-id total-amount) err-full-mint-reached)
      (if (not (is-err address-bns-name)) 
        (let 
          ((complete-bns-name (unwrap! address-bns-name err-bns-convert))
            (bns-name (as-max-len? (get name complete-bns-name) u20))
            (bns-namespace (as-max-len? (get namespace complete-bns-name) u9)))
            (if (and (is-some bns-name) (is-some bns-namespace)) 
              ;; bns address respects the criterias
              (set-nft-name next-id 
                (get-address-bns-name 
                  {name: (unwrap-panic bns-name),
                  namespace: (unwrap-panic bns-namespace)}))
              (set-nft-name next-id (concat "BitcoinDegen#" (contract-call? .conversions uint-to-string next-id)))))
        (if (is-some address-bnsx-name)
          (let 
            ((complete-bns-name (unwrap! address-bnsx-name err-bns-convert))
              (bns-name (as-max-len? (get name complete-bns-name) u20))
              (bns-namespace (as-max-len? (get namespace complete-bns-name) u9)))
              (if (and (is-some bns-name)  (is-some bns-namespace)) 
              ;; bnsx address respects the criterias
              (set-nft-name next-id 
                (get-address-bns-name 
                  {name: (unwrap-panic bns-name),
                  namespace: (unwrap-panic bns-namespace)}))
              (set-nft-name next-id (concat "BitcoinDegen#" (contract-call? .conversions uint-to-string next-id)))))
          ;; does not have bns address
          (set-nft-name next-id (concat "BitcoinDegen#" (contract-call? .conversions uint-to-string next-id)))))
      (ok (var-set last-id next-id)))))
