package models

import (
	"strings"
	"time"
)

type Board struct {
	Code        string `json:"code"`
	Description string `json:"description"`
}

type Thread struct {
	ID       int      `json:"id"`
	Title    string   `json:"title"`
	Text     string   `json:"text"`
	Creation string   `json:"creation"`
	Board    string   `json:"board"`
	Rating   *int     `json:"rating,omitempty"`
	Pinned   *bool    `json:"pinned,omitempty"`
	Files    []string `json:"files"`
}

func (t *Thread) GetCreationTime() time.Time {
	if parsed, err := time.Parse(time.RFC3339, t.Creation); err == nil {
		return parsed
	}
	return time.Now()
}

func (t *Thread) GetRatingValue() int {
	if t.Rating != nil {
		return *t.Rating
	}
	return 0
}

func (t *Thread) IsPinned() bool {
	return t.Pinned != nil && *t.Pinned
}

type ThreadDetail struct {
	ID       int      `json:"id"`
	Creation string   `json:"creation"`
	Title    string   `json:"title"`
	Text     string   `json:"text"`
	Board    string   `json:"board"`
	Files    []string `json:"files"`
}

func (td *ThreadDetail) GetCreationTime() time.Time {
	if parsed, err := time.Parse(time.RFC3339, td.Creation); err == nil {
		return parsed
	}
	return time.Now()
}

type Comment struct {
	ID       int      `json:"id"`
	Text     string   `json:"text"`
	Creation string   `json:"creation"`
	Files    []string `json:"files"`
}

func (c *Comment) GetCreationTime() time.Time {
	if parsed, err := time.Parse(time.RFC3339, c.Creation); err == nil {
		return parsed
	}
	return time.Now()
}

func (c *Comment) FormatText() string {
	text := c.Text
	// Простая замена #id на >>id для отображения
	// TODO: можно добавить более сложную обработку ссылок
	return strings.ReplaceAll(text, "#", ">>")
}

type FileInfo struct {
	URL      string
	Filename string
	IsImage  bool
	IsVideo  bool
}

func GetFileInfo(filePath string) FileInfo {
	filename := filePath
	if idx := strings.LastIndex(filePath, "/"); idx != -1 {
		filename = filePath[idx+1:]
	}

	ext := strings.ToLower(filePath)
	isImage := strings.HasSuffix(ext, ".jpg") ||
		strings.HasSuffix(ext, ".jpeg") ||
		strings.HasSuffix(ext, ".png") ||
		strings.HasSuffix(ext, ".gif") ||
		strings.HasSuffix(ext, ".webp")

	isVideo := strings.HasSuffix(ext, ".mp4") ||
		strings.HasSuffix(ext, ".webm")

	return FileInfo{
		URL:      "https://mkch.pooziqo.xyz" + filePath,
		Filename: filename,
		IsImage:  isImage,
		IsVideo:  isVideo,
	}
}

type APIError struct {
	Message string
	Code    int
}

func (e APIError) Error() string {
	return e.Message
}
