import { Maybe, Result } from "@repo/rdx-utils";
import { toEmptyString } from "../helpers";
import { City } from "./city";
import { Country } from "./country";
import { PostalCode } from "./postal-code";
import { Province } from "./province";
import { Street } from "./street";
import { ValueObject } from "./value-object";

export interface PostalAddressProps {
  street: Maybe<Street>;
  street2: Maybe<Street>;
  city: Maybe<City>;
  postalCode: Maybe<PostalCode>;
  province: Maybe<Province>;
  country: Maybe<Country>;
}

export type PostalAddressPatchProps = Partial<PostalAddressProps>;

export class PostalAddress extends ValueObject<PostalAddressProps> {
  protected static validate(values: PostalAddressProps) {
    return Result.ok(values);
  }

  static create(values: PostalAddressProps): Result<PostalAddress, Error> {
    const valueIsValid = PostalAddress.validate(values);

    if (valueIsValid.isFailure) {
      return Result.fail(valueIsValid.error);
    }
    return Result.ok(new PostalAddress(values));
  }

  public update(partial: Partial<PostalAddressPatchProps>): Result<PostalAddress, Error> {
    const updatedProps = {
      ...this.props,
      ...partial,
    } as PostalAddressProps;

    return PostalAddress.create(updatedProps);
  }

  get street(): Maybe<Street> {
    return this.props.street;
  }

  get street2(): Maybe<Street> {
    return this.props.street2;
  }

  get city(): Maybe<City> {
    return this.props.city;
  }

  get postalCode(): Maybe<PostalCode> {
    return this.props.postalCode;
  }

  get province(): Maybe<Province> {
    return this.props.province;
  }

  get country(): Maybe<Country> {
    return this.props.country;
  }

  getProps(): PostalAddressProps {
    return this.props;
  }

  toPrimitive() {
    return this.getProps();
  }

  toString() {
    return {
      street: toEmptyString(this.street, (value) => value.toString()),
      street2: toEmptyString(this.street2, (value) => value.toString()),
      city: toEmptyString(this.city, (value) => value.toString()),
      postal_code: toEmptyString(this.postalCode, (value) => value.toString()),
      province: toEmptyString(this.province, (value) => value.toString()),
      country: toEmptyString(this.country, (value) => value.toString()),
    };
  }

  toFormat(): string {
    return `${this.props.street}, ${this.props.street2}, ${this.props.city}, ${this.props.postalCode}, ${this.props.province}, ${this.props.country}`;
  }
}
