import { UserId } from '../value-objects/UserId';

export interface CompanyProps {
  id: string;
  name: string;
  ownerUserId: UserId;
  contactEmail: string | undefined;
  createdAt: Date;
}

export class Company {
  private readonly id: string;
  private readonly name: string;
  private readonly ownerUserId: UserId;
  private readonly contactEmail: string | undefined;
  private readonly createdAt: Date;

  private constructor(props: CompanyProps) {
    this.validateName(props.name);

    this.id = props.id;
    this.name = props.name;
    this.ownerUserId = props.ownerUserId;
    this.contactEmail = props.contactEmail;
    this.createdAt = props.createdAt;
  }

  private validateName(name: string): void {
    const trimmed = name?.trim();
    
    if (!trimmed) {
      throw new Error('Company name cannot be empty');
    }

    if (trimmed.length < 2) {
      throw new Error('Company name must be at least 2 characters long');
    }

    if (trimmed.length > 100) {
      throw new Error('Company name must be no more than 100 characters');
    }
  }

  public static create(props: {
    name: string;
    ownerUserId: UserId;
    contactEmail?: string;
  }): Company {
    return new Company({
      id: this.generateId(),
      name: props.name,
      ownerUserId: props.ownerUserId,
      contactEmail: props.contactEmail,
      createdAt: new Date(),
    });
  }

  public static rehydrate(props: {
    id: string;
    name: string;
    ownerUserId: string;
    contactEmail?: string;
    createdAt: Date;
  }): Company {
    return new Company({
      id: props.id,
      name: props.name,
      ownerUserId: UserId.fromString(props.ownerUserId),
      contactEmail: props.contactEmail,
      createdAt: props.createdAt,
    });
  }

  private static generateId(): string {
    // Simple UUID-like generation for now
    return `comp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  public getId(): string {
    return this.id;
  }

  public getName(): string {
    return this.name;
  }

  public getOwnerUserId(): UserId {
    return this.ownerUserId;
  }

  public getContactEmail(): string | undefined {
    return this.contactEmail;
  }

  public getCreatedAt(): Date {
    return this.createdAt;
  }
}