import { BaseEntity, Column, Entity, In, PrimaryColumn } from "typeorm";

@Entity()
export class PlexMovie extends BaseEntity
{
	@PrimaryColumn({ length: 27 })
	imdbId!: string;

	@Column({ type: "int", nullable: true, unique: true })
	tmdbId!: number|null;

	@Column()
	plexKey!: number;

	/**
	 * Check if a movie is on Plex given its TMDb ID
	 */
	public static async findPlexKey(tmdbId: number|string) {
		return (await PlexMovie.findOne({ where: { tmdbId } }))?.plexKey ?? null;
	}

	/**
	 * Get the set of IMDb IDs stored in the library
	 */
	public static async imdbSet() {
		let rows = await PlexMovie.createQueryBuilder("plex_movie")
			.select("imdbId")
			.getRawMany();
		return new Set(rows.map(row => <string>row.imdbId));
	}

	/**
	 * Insert a set of IMDb IDs into the database
	 */
	public static async insertMovies(movies: { imdbId: string, plexKey: number }[]) {
		await PlexMovie.createQueryBuilder()
			.insert()
			.into("plex_movie")
			.values([...movies].map(({imdbId, plexKey}) => ({ imdbId, tmdbId: null, plexKey })))
			.execute();
	}

	/**
	 * Remove the given set of IMDb IDs from the library
	 */
	public static async removeImdbSet(imdbIds: Set<string>) {
		await PlexMovie.delete({ imdbId: In([...imdbIds]) });
	}
}
