;; SatGuard Policy Registry
(define-constant err-nf (err u700))
(define-constant err-amt (err u701))
(define-constant err-unauth (err u702))
(define-data-var pol-nonce uint u0)
(define-constant POL-ACT u1)
(define-constant POL-EXP u2)
(define-constant POL-CAN u3)
(define-map policies {id: uint} {pid: uint,holder: principal,cov-amt: uint,prem: uint,start: uint,end: uint,st: uint})
(define-map user-pol-count {who: principal} {count: uint})
(define-read-only (get-policy (id uint)) (map-get? policies {id: id}))
(define-read-only (get-policy-count) (var-get pol-nonce))
(define-read-only (get-user-policy-count (who principal)) (default-to {count: u0} (map-get? user-pol-count {who: who})))
(define-public (create-policy (pid uint) (cov-amt uint) (dur uint))
(let ((pool (unwrap! (contract-call? .insurance-pool get-pool pid) err-nf))
(contrib (unwrap! (contract-call? .insurance-pool get-contrib pid tx-sender) err-unauth))
(nid (+ (var-get pol-nonce) u1))
(uc (get count (get-user-policy-count tx-sender))))
(asserts! (> cov-amt u0) err-amt)
(asserts! (<= cov-amt (get mx pool)) err-amt)
(map-set policies {id: nid} {pid: pid,holder: tx-sender,cov-amt: cov-amt,prem: (/ (* cov-amt u100) u10000),start: block-height,end: (+ block-height dur),st: POL-ACT})
(map-set user-pol-count {who: tx-sender} {count: (+ uc u1)})
(var-set pol-nonce nid)
(print {e: "policy-created",id: nid,pid: pid,holder: tx-sender})
(ok nid)))
(define-public (cancel-policy (id uint))
(let ((pol (unwrap! (get-policy id) err-nf)))
(asserts! (is-eq tx-sender (get holder pol)) err-unauth)
(map-set policies {id: id} (merge pol {st: POL-CAN}))
(print {e: "policy-cancelled",id: id})
(ok true)))