package storage

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"dejo_node/internal/transactions"
)

type BlockStore struct {
	Path string
}

func NewBlockStore(path string) *BlockStore {
	_ = os.MkdirAll(path, 0755)
	return &BlockStore{Path: path}
}

func (s *BlockStore) SaveBlock(block *transactions.Block) error {
	file := filepath.Join(s.Path, fmt.Sprintf("block_%03d.json", block.Index))
	data, err := json.MarshalIndent(block, "", "  ")
	if err != nil {
		return err
	}
	return ioutil.WriteFile(file, data, 0644)
}

func (s *BlockStore) LoadBlock(height int) (*transactions.Block, error) {
	file := filepath.Join(s.Path, fmt.Sprintf("block_%03d.json", height))
	data, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	var block transactions.Block
	err = json.Unmarshal(data, &block)
	if err != nil {
		return nil, err
	}
	return &block, nil
}

func (s *BlockStore) ListBlocks() ([]*transactions.Block, error) {
	files, err := ioutil.ReadDir(s.Path)
	if err != nil {
		return nil, err
	}
	var blocks []*transactions.Block
	for _, file := range files {
		if file.IsDir() || filepath.Ext(file.Name()) != ".json" {
			continue
		}
		heightStr := file.Name()[6:9]
		height, err := strconv.Atoi(heightStr)
		if err != nil {
			continue
		}
		block, err := s.LoadBlock(height)
		if err == nil {
			blocks = append(blocks, block)
		}
	}
	sort.Slice(blocks, func(i, j int) bool {
		return blocks[i].Index < blocks[j].Index
	})
	return blocks, nil
}

func (s *BlockStore) GetLatestBlock() (*transactions.Block, error) {
	blocks, err := s.ListBlocks()
	if err != nil || len(blocks) == 0 {
		return nil, fmt.Errorf("nenhum bloco disponível")
	}
	return blocks[len(blocks)-1], nil
}

func (s *BlockStore) GetBlockByIndex(index int) (*transactions.Block, error) {
	return s.LoadBlock(index)
}

func (s *BlockStore) LoadAll() ([]*transactions.Block, error) {
	return s.ListBlocks()
}