import { ApiClient } from './base'
import type { Profile } from './profile'

export interface AccountType {
  id: string
  name: string
  debitsPositive: boolean
}

export abstract class AccountTypes {
  public static readonly CHECKING: AccountType = {
    id: 'CHECKING',
    name: 'Checking',
    debitsPositive: true,
  }
  public static readonly SAVINGS: AccountType = {
    id: 'SAVINGS',
    name: 'Savings',
    debitsPositive: true,
  }
  public static readonly CREDIT_CARD: AccountType = {
    id: 'CREDIT_CARD',
    name: 'Credit Card',
    debitsPositive: false,
  }
  public static readonly BROKERAGE: AccountType = {
    id: 'BROKERAGE',
    name: 'Brokerage',
    debitsPositive: true,
  }

  public static of(id: string): AccountType {
    if (id === 'CHECKING') return AccountTypes.CHECKING
    if (id === 'SAVINGS') return AccountTypes.SAVINGS
    if (id === 'CREDIT_CARD') return AccountTypes.CREDIT_CARD
    if (id === 'BROKERAGE') return AccountTypes.BROKERAGE
    throw new Error('Unknown account type: ' + id)
  }
}

export interface Account {
  id: number
  createdAt: string
  archived: boolean
  type: string
  numberSuffix: string
  name: string
  currency: string
  description: string
}

export interface AccountCreationPayload {
  type: string
  numberSuffix: string
  name: string
  currency: string
  description: string
}

export class AccountApiClient extends ApiClient {
  readonly path: string

  constructor(profile: Profile) {
    super()
    this.path = `/profiles/${profile.name}/accounts`
  }

  async getAccounts(): Promise<Account[]> {
    return super.getJson(this.path)
  }

  async getAccount(id: number): Promise<Account> {
    return super.getJson(this.path + '/' + id)
  }

  async createAccount(data: AccountCreationPayload): Promise<Account> {
    return super.postJson(this.path, data)
  }

  async updateAccount(id: number, data: AccountCreationPayload): Promise<Account> {
    return super.putJson(this.path + '/' + id, data)
  }

  async deleteAccount(id: number): Promise<void> {
    return super.delete(this.path + '/' + id)
  }
}
