import {
	formatSignTime,
	getFileType,
	normalizeContractRecords,
	getUserIdFromSessionStorage,
	resolveContractFileUrl,
} from './contractRecords'

describe('contractRecords', () => {
	test('normalizes contract API payload into file cards', () => {
		const records = normalizeContractRecords({
			signTime: '2026-06-04T17:09:37.000+08:00',
			signerName: '靳世辉',
			merchantId: 12,
			file: [
				{
					id: 1,
					contractName: '合同图片.png',
					fileUrl: '/profile/upload/contract.png',
				},
				{
					id: 5,
					contractName: '我的合同',
					fileUrl: 'https://example.com/contract.pdf',
				},
			],
		})

		expect(records).toEqual([
			{
				id: 1,
				contractName: '合同图片.png',
				signTime: '2026.06.04 17:09:37',
				signerName: '靳世辉',
				merchantId: 12,
				fileUrl: '/profile/upload/contract.png',
				fileType: 'image',
			},
			{
				id: 5,
				contractName: '我的合同',
				signTime: '2026.06.04 17:09:37',
				signerName: '靳世辉',
				merchantId: 12,
				fileUrl: 'https://example.com/contract.pdf',
				fileType: 'pdf',
			},
		])
	})

	test('returns an empty list for missing file arrays', () => {
		expect(normalizeContractRecords(null)).toEqual([])
		expect(normalizeContractRecords({ file: null })).toEqual([])
	})

	test('resolves relative upload urls against the API origin', () => {
		expect(
			resolveContractFileUrl('/profile/upload/a.png', 'https://city.baoxianzhanggui.com/nightFragrance')
		).toBe('https://city.baoxianzhanggui.com/profile/upload/a.png')
		expect(resolveContractFileUrl('https://example.com/a.png', 'https://host/api')).toBe(
			'https://example.com/a.png'
		)
	})

	test('formats date and detects supported file types', () => {
		expect(formatSignTime('2026-06-04T17:09:37.000+08:00')).toBe('2026.06.04 17:09:37')
		expect(formatSignTime('')).toBe('')
		expect(getFileType('a.jpeg')).toBe('image')
		expect(getFileType('a.PDF')).toBe('pdf')
		expect(getFileType('http://example.com/file')).toBe('unknown')
	})

	test('reads userId from session storage user information', () => {
		const storage = {
			getItem(key) {
				const values = {
					userInfo: JSON.stringify({ id: 12 }),
				}
				return values[key] || ''
			},
		}

		expect(getUserIdFromSessionStorage(storage)).toBe(12)
	})

	test('falls back to direct session storage userId', () => {
		const storage = {
			getItem(key) {
				return key === 'userId' ? '12' : ''
			},
		}

		expect(getUserIdFromSessionStorage(storage)).toBe('12')
	})

	test('scans unknown session storage keys for nested merchant ids', () => {
		const values = {
			currentUser: JSON.stringify({
				data: {
					merchant: {
						id: 12,
					},
				},
			}),
		}
		const storage = {
			length: 1,
			key(index) {
				return Object.keys(values)[index]
			},
			getItem(key) {
				return values[key] || ''
			},
		}

		expect(getUserIdFromSessionStorage(storage)).toBe(12)
	})
})
