type EmployeeWithCompany = {
  id: string
  email: string
  firstName: string
  lastName: string
  role: string
  preferredLanguage?: string | null
  companyId: string
  company: {
    name: string
    slug: string
  }
}

type CompanySignupResult = {
  company: {
    id: string
    name: string
    slug: string
  }
  trialEndAt: Date
  emailDelivery?: unknown
}

type RenterProfile = {
  id: string
  firstName: string
  lastName: string
  email: string
  phone: string | null
  preferredLocale: string | null
  preferredCurrency: string | null
  emailVerified: boolean
  savedCompanies: Array<{ companyId: string }>
}

type SavedCompany = {
  id: string
  brand: {
    displayName: string | null
    subdomain: string | null
    logoUrl: string | null
  } | null
}

export function presentEmployeeSession(employee: EmployeeWithCompany, token?: string) {
  const data = {
    employee: {
      id: employee.id,
      email: employee.email,
      firstName: employee.firstName,
      lastName: employee.lastName,
      role: employee.role,
      preferredLanguage: employee.preferredLanguage,
      companyId: employee.companyId,
      companyName: employee.company.name,
      companySlug: employee.company.slug,
    },
  }

  return token ? { token, ...data } : data
}

export function presentCompanySignup(result: CompanySignupResult) {
  return {
    companyId: result.company.id,
    companyName: result.company.name,
    slug: result.company.slug,
    invitationId: null,
    trialEndsAt: result.trialEndAt.toISOString(),
    nextStep: 'workspace_created',
    emailDelivery: result.emailDelivery ?? { attempted: false, success: false, error: null },
  }
}

export function presentRenterProfile(renter: RenterProfile, companies: SavedCompany[]) {
  const companyMap = new Map(companies.map((company) => [company.id, company]))

  return {
    ...renter,
    savedCompanies: renter.savedCompanies.map((savedCompany) => ({
      id: savedCompany.companyId,
      brand: companyMap.get(savedCompany.companyId)?.brand ?? null,
    })),
  }
}
