;; p-m
(define-non-fungible-token p-m uint)

;; constants
(define-constant p-m-limit u6000)
(define-constant contract-owner tx-sender)

;; error messages
(define-constant ERR-ALL-MINTED (err u101))
(define-constant ERR-NOT-AUTH (err u102))

;; data maps and vars
(define-data-var ipfs-root (string-ascii 102) "ipfs://ipfs/QmYcrELFT5c9pjSygFFXk8jfVMHB5cBoWJDGafbHbATvrP/pm_")
(define-data-var p-m-index uint u0)

;;;;;;;;;;;;;;;;;;;;;;
;; SIP009 Functions ;;
;;;;;;;;;;;;;;;;;;;;;;
(define-read-only (lookup (uid uint))
  (ok (uint-to-ascii uid))
)

(define-read-only (get-last-token-id)
  (ok (var-get p-m-index))
)

(define-read-only (get-owner (id uint))
  (ok (nft-get-owner? p-m id))
)

(define-read-only (get-token-uri (token-id uint))
  (ok
    (some
      (concat
        (concat
          (var-get ipfs-root)
          (contract-call? .moon-project-v1 uint-to-ascii token-id)
        )
        ".json"
      )
    )
  )
)

(define-public (transfer (id uint) (sender principal) (recipient principal))
  (begin
    (asserts! (is-eq tx-sender sender) (err u103))
    (nft-transfer? p-m id sender recipient)
  )
)

;;;;;;;;;;;;;;;;;;;;
;; Core Functions ;;
;;;;;;;;;;;;;;;;;;;;

;; @desc core function for minting a p-m, four lunar-fragments are required as burns
(define-public (mint-p-m (lunar-fragment-id-1 uint) (lunar-fragment-id-2 uint) (lunar-fragment-id-3 uint) (lunar-fragment-id-4 uint))
  (let
    (
      (next-p-m-index (+ u1 (var-get p-m-index)))
    )
    ;; unsure if i can send to contract directly in line below, possible err
    (unwrap-panic (unwrap-panic (contract-call? .lunar-fragment transfer lunar-fragment-id-1 tx-sender .moon-project)))
    (unwrap-panic (unwrap-panic (contract-call? .lunar-fragment transfer lunar-fragment-id-2 tx-sender .moon-project)))
    (unwrap-panic (unwrap-panic (contract-call? .lunar-fragment transfer lunar-fragment-id-3 tx-sender .moon-project)))
    (unwrap-panic (unwrap-panic (contract-call? .lunar-fragment transfer lunar-fragment-id-4 tx-sender .moon-project)))
    (try! (nft-mint? p-m (var-get p-m-index) tx-sender))
    (unwrap-panic (contract-call? .moon-project-v1 update-user-p-ms-mint-count))
    (ok (var-set lunar-fragment-index next-lunar-fragment-index))
  )
)
