package postgres

import (
	"context"
	"database/sql"
	"errors"
	"time"

	"github.com/google/uuid"
	"github.com/rede5/gohorsejobs/backend/internal/core/domain/entity"
)

type CompanyRepository struct {
	db *sql.DB
}

func NewCompanyRepository(db *sql.DB) *CompanyRepository {
	return &CompanyRepository{db: db}
}

func (r *CompanyRepository) Save(ctx context.Context, company *entity.Company) (*entity.Company, error) {
	if company.ID == "" {
		company.ID = uuid.New().String()
	}

	query := `
		INSERT INTO core_companies (id, name, document, contact, status, created_at, updated_at)
		VALUES ($1, $2, $3, $4, $5, $6, $7)
		RETURNING id
	`

	err := r.db.QueryRowContext(ctx, query,
		company.ID,
		company.Name,
		company.Document,
		company.Contact,
		company.Status,
		company.CreatedAt,
		company.UpdatedAt,
	).Scan(&company.ID)

	if err != nil {
		return nil, err
	}
	return company, nil
}

func (r *CompanyRepository) FindByID(ctx context.Context, id string) (*entity.Company, error) {
	query := `SELECT id, name, document, contact, status, created_at, updated_at FROM core_companies WHERE id = $1`
	row := r.db.QueryRowContext(ctx, query, id)

	c := &entity.Company{}
	err := row.Scan(&c.ID, &c.Name, &c.Document, &c.Contact, &c.Status, &c.CreatedAt, &c.UpdatedAt)
	if err == sql.ErrNoRows {
		return nil, errors.New("company not found")
	}
	return c, err
}

func (r *CompanyRepository) Update(ctx context.Context, company *entity.Company) (*entity.Company, error) {
	company.UpdatedAt = time.Now()
	query := `
		UPDATE core_companies 
		SET name=$1, document=$2, contact=$3, status=$4, updated_at=$5
		WHERE id=$6
	`
	_, err := r.db.ExecContext(ctx, query,
		company.Name,
		company.Document,
		company.Contact,
		company.Status,
		company.UpdatedAt,
		company.ID,
	)
	return company, err
}

func (r *CompanyRepository) Delete(ctx context.Context, id string) error {
	query := `DELETE FROM core_companies WHERE id = $1`
	_, err := r.db.ExecContext(ctx, query, id)
	return err
}

func (r *CompanyRepository) FindAll(ctx context.Context) ([]*entity.Company, error) {
	query := `SELECT id, name, document, contact, status, created_at, updated_at FROM core_companies`
	rows, err := r.db.QueryContext(ctx, query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var companies []*entity.Company
	for rows.Next() {
		c := &entity.Company{}
		if err := rows.Scan(&c.ID, &c.Name, &c.Document, &c.Contact, &c.Status, &c.CreatedAt, &c.UpdatedAt); err != nil {
			return nil, err
		}
		companies = append(companies, c)
	}
	return companies, nil
}
