package development

import (
	"context"
	"git.markbailey.dev/cervers/ptpp/lib/database/dto"
	pterror "git.markbailey.dev/cervers/ptpp/lib/error"
	"git.markbailey.dev/cervers/ptpp/models/sqlite"
)

type OrganizationRepository struct{}

func (ur OrganizationRepository) CreateOrganization(o dto.Organization) (*dto.Organization, error) {
	ctx := context.Background()
	organization, err := TestQueries.CreateOrganization(ctx, sqlite.CreateOrganizationParams{
		Name:       o.Name,
		OwnerName:  o.OwnerName,
		OwnerPhone: o.OwnerPhone,
		OwnerEmail: o.OwnerEmail,
		CreatedAt:  &o.CreatedAt,
		DeletedAt:  o.DeletedAt,
		Authorized: o.Authorized,
		AuthToken:  o.AuthToken,
	})
	if err != nil {
		return nil, pterror.Wrap(err, "Error creating organization")
	}

	return &dto.Organization{
		Identifier: organization.Identifier,
		Name:       organization.Name,
		OwnerName:  organization.OwnerName,
		OwnerPhone: organization.OwnerPhone,
		OwnerEmail: organization.OwnerEmail,
		CreatedAt:  *organization.CreatedAt,
		DeletedAt:  organization.DeletedAt,
		Authorized: organization.Authorized,
		AuthToken:  organization.AuthToken,
	}, nil
}

func (ur OrganizationRepository) FindOrganizationByName(name string) (*dto.Organization, error) {
	ctx := context.Background()
	organization, err := TestQueries.FindOrganizationByName(ctx, name)
	if err != nil {
		return nil, pterror.Wrap(err, "Error finding organization by name")
	}

	return &dto.Organization{
		Identifier: organization.Identifier,
		Name:       organization.Name,
		OwnerName:  organization.OwnerName,
		OwnerPhone: organization.OwnerPhone,
		OwnerEmail: organization.OwnerEmail,
		CreatedAt:  *organization.CreatedAt,
		DeletedAt:  organization.DeletedAt,
		Authorized: organization.Authorized,
		AuthToken:  organization.AuthToken,
	}, nil
}

func (ur OrganizationRepository) FindOrganizationById(id int64) (*dto.Organization, error) {
	ctx := context.Background()
	organization, err := TestQueries.FindOrganizationById(ctx, id)
	if err != nil {
		return nil, pterror.Wrap(err, "Error finding organization by ID")
	}

	return &dto.Organization{
		Identifier: organization.Identifier,
		Name:       organization.Name,
		OwnerName:  organization.OwnerName,
		OwnerPhone: organization.OwnerPhone,
		OwnerEmail: organization.OwnerEmail,
		CreatedAt:  *organization.CreatedAt,
		DeletedAt:  organization.DeletedAt,
		Authorized: organization.Authorized,
		AuthToken:  organization.AuthToken,
	}, nil
}
