package production

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

type OrganizationRepository struct{}

func (or OrganizationRepository) CreateOrganization(o dto.Organization) (*dto.Organization, error) {
	ctx := context.Background()

	organization, err := ProdQueries.CreateOrganization(ctx, postgres.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, err
	}

	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 (or OrganizationRepository) FindOrganizationByName(name string) (*dto.Organization, error) {
	ctx := context.Background()
	organization, err := ProdQueries.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 (or OrganizationRepository) FindOrganizationById(id int64) (*dto.Organization, error) {
	ctx := context.Background()
	organization, err := ProdQueries.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
}
