import { z } from "zod";

export const GetTitleDetailsInput = z.object({
	id: z.string(),
});

const CommonTitleDetailsSchema = z.object({
	id: z.string(),
	title: z.string(),
	originalTitle: z.string(),
	year: z.number().nullable(),
	poster: z.string().nullable(),
	backdrop: z.string().nullable(),
	rating: z.number().nullable(),
	genres: z.array(
		z.object({
			id: z.string(),
			name: z.string(),
		}),
	),
	synopsis: z.string().nullable(),
	cast: z.array(
		z.object({
			id: z.string(),
			name: z.string(),
			character: z.string().nullable(),
			profilePicture: z.string().nullable(),
			order: z.number().nullable(),
		}),
	),
	crew: z.array(
		z.object({
			id: z.string(),
			name: z.string(),
			job: z.string().nullable(),
			department: z.string().nullable(),
			profilePicture: z.string().nullable(),
			order: z.number().nullable(),
		}),
	),
	similarTitles: z.array(
		z.object({
			id: z.string(),
			title: z.string(),
			year: z.number().nullable(),
			poster: z.string().nullable(),
		}),
	),
});

const MovieDetailsSchema = CommonTitleDetailsSchema.extend({
	type: z.literal("MOVIE"),
	runtimeSeconds: z.number().nullable(),
});

export const SeriesSeasonSchema = z.object({
	seasonId: z.string(),
	seasonNumber: z.number(),
	title: z.string().nullable(),
	episodes: z.number(),
});

export type SeriesSeason = z.infer<typeof SeriesSeasonSchema>;

const SeriesDetailsSchema = CommonTitleDetailsSchema.extend({
	type: z.literal("SERIES"),
	seasonsCount: z.number(),
	episodesCount: z.number(),
	seasons: z.array(SeriesSeasonSchema),
});

export const GetTitleDetailsOutput = z.discriminatedUnion("type", [
	MovieDetailsSchema,
	SeriesDetailsSchema,
]);

export type GetTitleDetailsInput = z.infer<typeof GetTitleDetailsInput>;
export type GetTitleDetailsOutput = z.infer<typeof GetTitleDetailsOutput>;

export const SearchTitlesInput = z.object({
	query: z.string().min(1),
});

export const SearchTitlesOutput = z.array(
	z.object({
		id: z.string(),
		title: z.string(),
		year: z.number().nullable(),
		poster: z.string().nullable(),
		type: z.string(),
	}),
);

export type SearchTitlesInput = z.infer<typeof SearchTitlesInput>;
export type SearchTitlesOutput = z.infer<typeof SearchTitlesOutput>;

export const GetSeasonEpisodesInput = z.object({
	titleId: z.string(),
	seasonId: z.string(),
});

export const GetSeasonEpisodesOutput = z.object({
	seasonId: z.string(),
	seasonNumber: z.number(),
	seasonTitle: z.string().nullable(),
	episodeCount: z.number(),
	episodes: z.array(
		z.object({
			id: z.string(),
			episodeNumber: z.number(),
			title: z.string(),
			overview: z.string().nullable(),
			airDate: z.string().nullable(),
			runtimeSeconds: z.number().nullable(),
			backgroundUrl: z.string().nullable(),
		}),
	),
});

export type GetSeasonEpisodesInput = z.infer<typeof GetSeasonEpisodesInput>;
export type GetSeasonEpisodesOutput = z.infer<typeof GetSeasonEpisodesOutput>;
