// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package lunatask

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"time"
)

// Person is a contact in Lunatask's relationship tracker.
// FirstName and LastName are encrypted client-side and will be null when read.
type Person struct {
	ID                   string    `json:"id"`
	RelationshipStrength *string   `json:"relationship_strength"`
	Sources              []Source  `json:"sources"`
	CreatedAt            time.Time `json:"created_at"`
	UpdatedAt            time.Time `json:"updated_at"`
}

// CreatePersonRequest defines a new person.
// Use [PersonBuilder] for a fluent construction API.
type CreatePersonRequest struct {
	FirstName            *string `json:"first_name,omitempty"`
	LastName             *string `json:"last_name,omitempty"`
	RelationshipStrength *string `json:"relationship_strength,omitempty"`
	Source               *string `json:"source,omitempty"`
	SourceID             *string `json:"source_id,omitempty"`
}

// personResponse wraps a single person from the API.
type personResponse struct {
	Person Person `json:"person"`
}

// peopleResponse wraps a list of people from the API.
type peopleResponse struct {
	People []Person `json:"people"`
}

// ListPeopleOptions filters people by source integration.
type ListPeopleOptions struct {
	Source   *string
	SourceID *string
}

// ListPeople returns all people, optionally filtered. Pass nil for all.
func (c *Client) ListPeople(ctx context.Context, opts *ListPeopleOptions) ([]Person, error) {
	path := "/people"

	if opts != nil {
		params := url.Values{}
		if opts.Source != nil && *opts.Source != "" {
			params.Set("source", *opts.Source)
		}

		if opts.SourceID != nil && *opts.SourceID != "" {
			params.Set("source_id", *opts.SourceID)
		}

		if len(params) > 0 {
			path = fmt.Sprintf("%s?%s", path, params.Encode())
		}
	}

	resp, _, err := doJSON[peopleResponse](ctx, c, http.MethodGet, path, nil)
	if err != nil {
		return nil, err
	}

	return resp.People, nil
}

// GetPerson fetches a person by ID. Name fields will be null (E2EE).
func (c *Client) GetPerson(ctx context.Context, personID string) (*Person, error) {
	if personID == "" {
		return nil, fmt.Errorf("%w: person ID cannot be empty", ErrBadRequest)
	}

	resp, _, err := doJSON[personResponse](ctx, c, http.MethodGet, "/people/"+personID, nil)
	if err != nil {
		return nil, err
	}

	return &resp.Person, nil
}

// CreatePerson adds a person. Returns (nil, nil) if a duplicate exists
// with matching source/source_id.
func (c *Client) CreatePerson(ctx context.Context, person *CreatePersonRequest) (*Person, error) {
	resp, noContent, err := doJSON[personResponse](ctx, c, http.MethodPost, "/people", person)
	if err != nil {
		return nil, err
	}

	if noContent {
		// Intentional: duplicate exists (HTTP 204), not an error
		return nil, nil //nolint:nilnil
	}

	return &resp.Person, nil
}

// DeletePerson removes a person and returns their final state.
func (c *Client) DeletePerson(ctx context.Context, personID string) (*Person, error) {
	if personID == "" {
		return nil, fmt.Errorf("%w: person ID cannot be empty", ErrBadRequest)
	}

	resp, _, err := doJSON[personResponse](ctx, c, http.MethodDelete, "/people/"+personID, nil)
	if err != nil {
		return nil, err
	}

	return &resp.Person, nil
}
