import type {NonRecursiveType, StaticPartOfArray, VariablePartOfArray, SetArrayAccess} from './internal/index.d.ts';
import type {TupleLength} from './tuple-length.d.ts';
import type {ApplyDefaultOptions} from './apply-default-options.d.ts';
import type {IsReadonlyArray} from './is-readonly-array.d.ts';
import type {OmitIndexSignature} from './omit-index-signature.d.ts';
import type {UnionMax} from './union-max.d.ts';
import type {UnionMin} from './union-min.d.ts';
import type {IsNever} from './is-never.d.ts';
import type {If} from './if.d.ts';
import type {UnknownArray} from './unknown-array.d.ts';
import type {SharedUnionFields} from './shared-union-fields.d.ts'; // For `@link`

/**
Options for the `SharedUnionFieldsDeep` type.

@see {@link SharedUnionFieldsDeep}
*/
export type SharedUnionFieldsDeepOptions = {
	/**
	When set to true, this option impacts each element within arrays or tuples. If all union values are arrays or tuples, it constructs an array of the shortest possible length, ensuring every element exists in the union array.

	@default false
 	*/
	recurseIntoArrays?: boolean;
};

type DefaultSharedUnionFieldsDeepOptions = {
	recurseIntoArrays: false;
};

/**
Create a type with shared fields from a union of object types, deeply traversing nested structures.

Use the {@link SharedUnionFieldsDeepOptions `Options`} to specify the behavior for arrays.

In a generic function, use concrete option values before relying on the array shape of the result. While any option is generic, TypeScript can read the result as if the default options were used.

Use-cases:
- You want a safe object type where each key exists in the union object.
- You want to focus on the common fields of the union type and don't want to have to care about the other fields.

@example
```
import type {SharedUnionFieldsDeep} from 'type-fest';

type Cat = {
	info: {
		name: string;
		type: 'cat';
		catType: string;
	};
};

type Dog = {
	info: {
		name: string;
		type: 'dog';
		dogType: string;
	};
};

function displayPetInfo(petInfo: (Cat | Dog)['info']) {
	// typeof petInfo =>
	// {
	// 	name: string;
	// 	type: 'cat';
	// 	catType: string; // Needn't care about this field, because it's not a common pet info field.
	// } | {
	// 	name: string;
	// 	type: 'dog';
	// 	dogType: string; // Needn't care about this field, because it's not a common pet info field.
	// }

	// petInfo type is complex and have some needless fields

	console.log('name:', petInfo.name);
	console.log('type:', petInfo.type);
}

function displayPetInfoWithSharedUnionFieldsDeep(petInfo: SharedUnionFieldsDeep<Cat | Dog>['info']) {
	// typeof petInfo =>
	// {
	// 	name: string;
	// 	type: 'cat' | 'dog';
	// }

	// petInfo type is simple and clear

	console.log('name:', petInfo.name);
	console.log('type:', petInfo.type);
}
```

@see {@link SharedUnionFields}

@category Object
@category Union
*/
export type SharedUnionFieldsDeep<Union, Options extends SharedUnionFieldsDeepOptions = {}> =
	ApplyDefaultOptions<SharedUnionFieldsDeepOptions, DefaultSharedUnionFieldsDeepOptions, Options> extends infer OptionsWithDefaults extends Required<SharedUnionFieldsDeepOptions>
		? _SharedUnionFieldsDeep<Union, OptionsWithDefaults>
		: never;

// Recursive calls reuse the resolved options instead of applying defaults again.
type _SharedUnionFieldsDeep<Union, OptionsWithDefaults extends Required<SharedUnionFieldsDeepOptions>> =
	// `Union extends` will convert `Union`
	// to a [distributive conditional type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
	// But this is not what we want, so we need to wrap `Union` with `[]` to prevent it.
	[Union] extends [NonRecursiveType | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown>]
		? Union
		: [Union] extends [UnknownArray]
			? OptionsWithDefaults['recurseIntoArrays'] extends true
				// With no fixed length or prefix, the tuple builder only appends a rest array. Build it directly so recursive elements stay lazy.
				? [TupleLength<Union>, StaticPartOfArray<Union>['length']] extends [never, 0]
					? If<IsReadonlyArray<Union>, ReadonlyArray<_SharedUnionFieldsDeep<Union[number], OptionsWithDefaults>>, Array<_SharedUnionFieldsDeep<Union[number], OptionsWithDefaults>>>
					: SharedArrayUnionFieldsDeep<Union, OptionsWithDefaults>
				: Union
			: [Union] extends [object]
				? SharedObjectUnionFieldsDeep<Union, OptionsWithDefaults>
				: Union;

/**
Same as `SharedUnionFieldsDeep`, but accepts only `object`s as inputs. Internal helper for `SharedUnionFieldsDeep`.
*/
type SharedObjectUnionFieldsDeep<Union, Options extends Required<SharedUnionFieldsDeepOptions>> =
	// Merge shared index domains and declared fields before mapping them, retaining known properties without distributing the union.
	(Pick<Union, keyof Union> & Pick<Union, keyof OmitIndexSignature<Union> & keyof Union>) extends infer Shared
		? {
			[Key in keyof Shared]:
			Shared[Key] extends NonRecursiveType
				? Shared[Key]
				// Remove `undefined` from the union to support optional
				// fields, then recover `undefined` if union was already undefined.
				: _SharedUnionFieldsDeep<Exclude<Shared[Key], undefined>, Options> | (
					undefined extends Required<Shared>[Key] ? undefined : never
				)
		}
		: Union;

/**
Same as `SharedUnionFieldsDeep`, but accepts only `UnknownArray`s as inputs. Internal helper for `SharedUnionFieldsDeep`.
*/
type SharedArrayUnionFieldsDeep<Union extends UnknownArray, Options extends Required<SharedUnionFieldsDeepOptions>> =
	// Restore the readonly modifier of the array.
	SetArrayAccess<
		InternalSharedArrayUnionFieldsDeep<Union, Options>,
		IsReadonlyArray<Union>
	>;

/**
Internal helper for `SharedArrayUnionFieldsDeep`. Needn't care the `readonly` modifier of arrays.
*/
type InternalSharedArrayUnionFieldsDeep<
	Union extends UnknownArray,
	Options extends Required<SharedUnionFieldsDeepOptions>,
	ResultTuple extends UnknownArray = [],
> =
	// We should build a minimum possible length tuple where each element in the tuple exists in the union tuple.
	IsNever<TupleLength<Union>> extends true
		// Rule 1: If all the arrays in the union have non-fixed lengths,
		// like `Array<string> | [number, ...string[]]`
		// we should build a tuple that is [the_fixed_parts_of_union, ...the_rest_of_union[]].
		// For example: `InternalSharedArrayUnionFieldsDeep<Array<string> | [number, ...string[]]>`
		// => `[string | number, ...string[]]`.
		? ResultTuple['length'] extends UnionMax<StaticPartOfArray<Union>['length']>
			? [
				// The fixed-length part of the tuple.
				...ResultTuple,
				// The rest of the union.
				// Due to `ResultTuple` is the maximum possible fixed-length part of the tuple,
				// so we can use `StaticPartOfArray` to get the rest of the union.
				...Array<
					_SharedUnionFieldsDeep<VariablePartOfArray<Union>[number], Options>
				>,
			]
			// Build the fixed-length tuple recursively.
			: InternalSharedArrayUnionFieldsDeep<
				Union, Options,
				[...ResultTuple, _SharedUnionFieldsDeep<Union[ResultTuple['length']], Options>]
			>
		// Rule 2: If at least one of the arrays in the union have fixed lengths,
		// like `Array<string> | [number, string]`,
		// we should build a tuple of the smallest possible length to ensure any
		// item in the result tuple exists in the union tuple.
		// For example: `InternalSharedArrayUnionFieldsDeep<Array<string> | [number, string]>`
		// => `[string | number, string]`.
		: ResultTuple['length'] extends UnionMin<TupleLength<Union>>
			? ResultTuple
			// As above, build tuple recursively.
			: InternalSharedArrayUnionFieldsDeep<
				Union, Options,
				[...ResultTuple, _SharedUnionFieldsDeep<Union[ResultTuple['length']], Options>]
			>;

export {};
