package company

import (
	"context"
	"git.makki.io/makki/libgo/dbu"
	"github.com/guregu/null/v5"
	"log/slog"
	"reflect"
)

type Company struct {
	ClID     int64       `db:"clid" json:"-"`
	ID       int64       `db:"id"`
	Code     string      `db:"code"`
	Name     null.String `db:"name"`
	IsActive bool        `db:"is_active"`
	Notes    null.String `db:"notes"`

	Tmpl null.String `db:"tmpl"`
}

func New() *Company {
	m := &Company{
		IsActive: true,
	}

	// m.__DetailStruct__ = dbu.NewDetailData[*__DetailStruct__]("__sql_filename__", "__sql_masterlink_field__", "__struct_master_field_link__", true)

	return m
}

func DbRead(ctx context.Context, id int64) (*Company, error) {
	rp, err := dbu.NewRepoWithFile(ctx, "cm", nil)
	if err != nil {
		return nil, err
	}
	data := New()
	//rp.AddDetail(data.Auths)
	err = rp.Read(id, data)
	return data, err
}

func (m *Company) GetIDVal() int64 {
	return m.ID
}

func (m *Company) SetMasterLinkVal(masterField string, val int64) {
	reflect.ValueOf(m).Elem().FieldByName(masterField).SetInt(val)
}

func DbDelete(ctx context.Context, id int64, log bool, usrID *int64) error {
	tx, err := dbu.DB.Begin(ctx)
	if err != nil {
		return err
	}
	defer tx.Rollback(ctx)

	rp, err := dbu.NewRepoWithFile(ctx, "cm", tx)
	if err != nil {
		return err
	}

	if log {
		var oldData *Company
		oldData, err = DbRead(ctx, id)
		if err != nil {
			return dbu.ParsedErrSuppressNoRows(err)
		}
		err = dbu.DB.LogDMLTx("d", "cm", oldData.ID, usrID, "", oldData, nil, tx)
		if err != nil {
			slog.Error(err.Error())
		}
	}

	err = rp.Delete(id)
	if err != nil {
		return err
	}

	return tx.Commit(ctx)
}

func (m *Company) DbCreate(ctx context.Context, clID int64, log bool, usrID *int64) error {
	m.ClID = clID

	rp, err := dbu.NewRepoWithFile(ctx, "cm", nil)
	if err != nil {
		return err
	}

	err = rp.Create(m)
	if err != nil {
		return err
	}

	if log {
		err = dbu.DB.LogDMLTx("c", "cm", m.ID, usrID, "", nil, m, nil)
		if err != nil {
			slog.Error(err.Error())
		}
	}

	return nil
}

func (m *Company) DbUpdate(ctx context.Context, log bool, usrID *int64) error {
	tx, err := dbu.DB.Begin(ctx)
	if err != nil {
		return err
	}
	defer tx.Rollback(ctx)

	rp, err := dbu.NewRepoWithFile(ctx, "cm", tx)
	if err != nil {
		return err
	}

	if log {
		var oldData *Company
		oldData, err = DbRead(ctx, m.ID)
		if err != nil {
			return err
		}
		err = dbu.DB.LogDMLTx("u", "cm", oldData.ID, usrID, "", oldData, m, tx)
		if err != nil {
			slog.Error(err.Error())
		}
	}

	err = rp.Update(m.ID, m)
	if err != nil {
		return err
	}

	return tx.Commit(ctx)
}
