package model

import (
	"fmt"
	"strings"
	"time"
)

type (
    Record struct {
        Type string `json:"$type"`
        CreatedAt string `json:"createdAt"`
        Text string `json:"text"`
    }

    Profile struct {
        DID string `json:"did"`
        Handle string `json:"handle"`
        Avatar string `json:"avatar"`
        DisplayName string `json:"displayName"`
        CreatedAt string `json:"createdAt"`
    }

    PostImage struct {
        Thumbnail string `json:"thumb"`
        Fullsize string `json:"fullsize"`
        Alt string `json:"alt"`
    }

    EmbedMedia struct {
        Images []PostImage `json:"images"`
    }

    Embed struct {
        Media EmbedMedia `json:"media"`
    }

    Post struct {
        Author Profile `json:"author"`
        Record Record `json:"record"`
        ReplyCount int `json:"replyCount"`
        RepostCount int `json:"repostCount"`
        LikeCount int `json:"likeCount"`
        QuoteCount int `json:"quoteCount"`
        Embed *Embed `json:"embed"`
        URI string `json:"uri"`
    }

    ThreadViewPost struct {
        Post Post `json:"post"`
        Replies []*ThreadViewPost `json:"replies"`
    }
)

func (record *Record) CreatedAtPrint() (string, error) {
    t, err := record.CreatedAtTime()
    if err != nil { return "", err }
    return t.Format("15:04, 2 February 2006"), nil
}

func (record *Record) CreatedAtTime() (time.Time, error) {
    return time.Parse("2006-01-02T15:04:05Z", record.CreatedAt)
}

func (post *Post) HasImage() bool {
    return post.Embed != nil && len(post.Embed.Media.Images) > 0
}

func (post *Post) PostID() string {
    return strings.TrimPrefix(
        post.URI,
        fmt.Sprintf("at://%s/app.bsky.feed.post/", post.Author.DID),
    )
}

func (post *Post) BskyURL() string {
    return fmt.Sprintf(
        "https://bsky.app/profile/%s/post/%s",
        post.Author.DID,
        post.PostID(),
    )
}
