import { Arg, Mutation, Query, Resolver } from "@aet/gql-tools/macro"
import { File } from "~/shared/models/index"
import { getDocs } from "../../couchdb"
import { setFile } from "./FileResolver"

@Resolver()
export class TagResolver {
  @Query()
  async tags(): Promise<string[]> {
    const files = await getDocs()
    return Array.from(new Set(files.flatMap(s => s.tags)))
  }

  @Mutation()
  async deleteTag(@Arg() tag: string): Promise<File[]> {
    return Promise.all(
      (await getDocs())
        .filter(file => file.tags.includes(tag))
        .map(file => {
          const tags = file.tags.filter(t => t !== tag)
          return setFile(file.id, { tags })
        }),
    )
  }

  @Mutation()
  async renameTag(@Arg() oldTag: string, @Arg() newTag: string): Promise<File[]> {
    return Promise.all(
      (await getDocs())
        .filter(file => file.tags.includes(oldTag))
        .map(file => {
          const tags = file.tags.map(tag => (tag === oldTag ? newTag : tag))
          return setFile(file.id, { tags })
        }),
    )
  }
}
