/**
 * Author: Marco Visin
 * Date: 2025-06-02
 * Updated to support Bearer token authentication
 */

import {
	IAuthenticateGeneric,
	ICredentialTestRequest,
	ICredentialType,
	INodeProperties,
	Icon,
} from 'n8n-workflow';

export class InNotesApi implements ICredentialType {
	name = 'inNotesApi';
	displayName = 'InNotes API';
	documentationUrl = 'https://innotes.me';
	icon: Icon = 'file:Logo_128.png';
	properties: INodeProperties[] = [
		{
			displayName: 'Base URL',
			name: 'baseUrl',
			type: 'string',
			default: 'https://innotes.me',
			description: 'The base URL of your InNotes instance',
			required: true,
		},
		{
			displayName: 'Authentication Method',
			name: 'authMethod',
			type: 'options',
			options: [
				{
					name: 'Bearer Token',
					value: 'token',
				},
				{
					name: 'Username/Password (Legacy)',
					value: 'credentials',
				},
			],
			default: 'token',
			description: 'Choose your authentication method. Bearer token is recommended.',
		},
		{
			displayName: 'Bearer Token',
			name: 'token',
			type: 'string',
			typeOptions: {
				password: true,
			},
			default: '',
			description: 'Your InNotes API Bearer token. Generate one in your dashboard settings.',
			required: true,
			displayOptions: {
				show: {
					authMethod: ['token'],
				},
			},
		},
		{
			displayName: 'Username',
			name: 'username',
			type: 'string',
			default: '',
			description: 'Your InNotes username',
			required: true,
			displayOptions: {
				show: {
					authMethod: ['credentials'],
				},
			},
		},
		{
			displayName: 'Password',
			name: 'password',
			type: 'string',
			typeOptions: {
				password: true,
			},
			default: '',
			description: 'Your InNotes password',
			required: true,
			displayOptions: {
				show: {
					authMethod: ['credentials'],
				},
			},
		},
	];

	authenticate: IAuthenticateGeneric = {
		type: 'generic',
		properties: {
			headers: {
				'Authorization': '={{$credentials.authMethod === "token" ? "Bearer " + $credentials.token : undefined}}',
				'username': '={{$credentials.authMethod === "credentials" ? $credentials.username : undefined}}',
				'password': '={{$credentials.authMethod === "credentials" ? $credentials.password : undefined}}',
			},
		},
	};

	test: ICredentialTestRequest = {
		request: {
			baseURL: '={{$credentials.baseUrl}}',
			url: '/api/user',
			method: 'GET',
		},
	};
}
