package database

import (
	"Portifolio/internal/model"
	"database/sql"
	"fmt"
	"time"

	_ "github.com/mattn/go-sqlite3"
)

func GetCategoryByName(db *sql.DB, companyID int, name string) (model.RevenueCategory, error) {
	var rc model.RevenueCategory
	err := db.QueryRow(
		`SELECT id, company_id, parent_id, name FROM category WHERE company_id = ? AND name = ?`,
		companyID, name,
	).Scan(&rc.ID, &rc.CompanyID, &rc.ParentID, &rc.Name)
	if err == sql.ErrNoRows {
		return rc, fmt.Errorf("category %q not found for company %d", name, companyID)
	}
	if err != nil {
		return rc, fmt.Errorf("get category by name: %w", err)
	}
	return rc, nil
}

func GetPeriodByID(db *sql.DB, periodID int) (model.Period, error) {
	var p model.Period
	var start, end string
	err := db.QueryRow(
		`SELECT type, year, idx, start_date, end_date FROM periods WHERE id = ?`,
		periodID,
	).Scan(&p.Type, &p.Year, &p.Index, &start, &end)
	if err == sql.ErrNoRows {
		return p, fmt.Errorf("period %d not found", periodID)
	}
	if err != nil {
		return p, fmt.Errorf("get period by id: %w", err)
	}
	p.Start, _ = time.Parse("2006-01-02", start)
	p.End, _ = time.Parse("2006-01-02", end)
	return p, nil
}
