package json

import (
	"encoding/json"
	"fmt"
	"os"

	"git.warky.dev/wdevs/relspecgo/pkg/models"
	"git.warky.dev/wdevs/relspecgo/pkg/readers"
)

// Reader implements the readers.Reader interface for JSON format
type Reader struct {
	options *readers.ReaderOptions
}

// NewReader creates a new JSON reader with the given options
func NewReader(options *readers.ReaderOptions) *Reader {
	return &Reader{
		options: options,
	}
}

// ReadDatabase reads and parses JSON input, returning a Database model
func (r *Reader) ReadDatabase() (*models.Database, error) {
	if r.options.FilePath == "" {
		return nil, fmt.Errorf("file path is required for JSON reader")
	}

	content, err := os.ReadFile(r.options.FilePath)
	if err != nil {
		return nil, fmt.Errorf("failed to read file: %w", err)
	}

	var db models.Database
	if err := json.Unmarshal(content, &db); err != nil {
		return nil, fmt.Errorf("failed to unmarshal JSON: %w", err)
	}

	return &db, nil
}

// ReadSchema reads and parses JSON input, returning a Schema model
func (r *Reader) ReadSchema() (*models.Schema, error) {
	if r.options.FilePath == "" {
		return nil, fmt.Errorf("file path is required for JSON reader")
	}

	content, err := os.ReadFile(r.options.FilePath)
	if err != nil {
		return nil, fmt.Errorf("failed to read file: %w", err)
	}

	var schema models.Schema
	if err := json.Unmarshal(content, &schema); err != nil {
		return nil, fmt.Errorf("failed to unmarshal JSON: %w", err)
	}

	return &schema, nil
}

// ReadTable reads and parses JSON input, returning a Table model
func (r *Reader) ReadTable() (*models.Table, error) {
	if r.options.FilePath == "" {
		return nil, fmt.Errorf("file path is required for JSON reader")
	}

	content, err := os.ReadFile(r.options.FilePath)
	if err != nil {
		return nil, fmt.Errorf("failed to read file: %w", err)
	}

	var table models.Table
	if err := json.Unmarshal(content, &table); err != nil {
		return nil, fmt.Errorf("failed to unmarshal JSON: %w", err)
	}

	return &table, nil
}
