package biz

import (
	"context"
	"time"

	"github.guxuan/haibei/internal/mods/common/dal"
	"github.guxuan/haibei/internal/mods/common/schema"
	"github.guxuan/haibei/pkg/errors"
	"github.guxuan/haibei/pkg/util"
)

// Defining the `Company` business logic.
type Company struct {
	Trans      *util.Trans
	CompanyDAL *dal.Company
}

// Query companies from the data access object based on the provided parameters and options.
func (a *Company) Query(ctx context.Context, params schema.CompanyQueryParam) (*schema.CompanyQueryResult, error) {
	params.Pagination = true

	result, err := a.CompanyDAL.Query(ctx, params, schema.CompanyQueryOptions{
		QueryOptions: util.QueryOptions{
			OrderFields: []util.OrderByParam{
				{Field: "created_at", Direction: util.DESC},
			},
		},
	})
	if err != nil {
		return nil, err
	}
	return result, nil
}

// Get the specified company from the data access object.
func (a *Company) Get(ctx context.Context, id uint) (*schema.Company, error) {
	company, err := a.CompanyDAL.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if company == nil {
		return nil, errors.NotFound("", "Company not found")
	}
	return company, nil
}

// Create a new company in the data access object.
func (a *Company) Create(ctx context.Context, formItem *schema.CompanyForm) (*schema.Company, error) {
	company := &schema.Company{}

	if err := formItem.FillTo(company); err != nil {
		return nil, err
	}

	err := a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.CompanyDAL.Create(ctx, company); err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return company, nil
}

// Update the specified company in the data access object.
func (a *Company) Update(ctx context.Context, id uint, formItem *schema.CompanyForm) error {
	company, err := a.CompanyDAL.Get(ctx, id)
	if err != nil {
		return err
	} else if company == nil {
		return errors.NotFound("", "Company not found")
	}

	if err := formItem.FillTo(company); err != nil {
		return err
	}
	company.UpdatedAt = time.Now()

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.CompanyDAL.Update(ctx, company); err != nil {
			return err
		}
		return nil
	})
}

// Delete the specified company from the data access object.
func (a *Company) Delete(ctx context.Context, id uint) error {
	exists, err := a.CompanyDAL.Exists(ctx, id)
	if err != nil {
		return err
	} else if !exists {
		return errors.NotFound("", "Company not found")
	}

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.CompanyDAL.Delete(ctx, id); err != nil {
			return err
		}
		return nil
	})
}
