<template>
	<ObjectList class="p-5" :options="logsOptions" />
</template>

<script>
import { isMobile } from '../../utils/device';
import { duration } from '../../utils/format';
import { t } from '../../utils/i18n';
import ObjectList from '../ObjectList.vue';

// Job type translation function
function jobTypeI18n(type) {
	return t(type) || type;
}

// Status translation function
function statusI18n(status) {
	return t(status) || status;
}

// Relative time formatting
function formatTimeRelative(time) {
	if (!time) return '';
	const date = typeof time === 'string' ? new Date(time) : time;
	const now = new Date();
	const diff = (now.getTime() - date.getTime()) / 1000;
	if (diff < 60) return t('Just now');
	if (diff < 3600) return t('{minutes} minutes ago', { minutes: Math.floor(diff / 60) });
	if (diff < 86400) return t('{hours} hours ago', { hours: Math.floor(diff / 3600) });
	if (diff < 2592000) return t('{days} days ago', { days: Math.floor(diff / 86400) });
	return date.toLocaleDateString();
}

export default {
	name: 'SiteJobs',
	props: ['name'],
	components: {
		ObjectList
	},
	computed: {
		logsOptions() {
			const pagetype = 'Site';
			return {
				pagetype: 'Agent Job',
				filters: {
					site: this.name
				},
				route(row) {
					return {
						name: 'Site Job',
						params: { id: row.name }
					};
				},
				orderBy: 'creation desc',
				searchField: 'job_type',
				fields: ['end', 'job_id'],
				filterControls() {
					return [
						{
							type: 'select',
							label: t('Status'),
							fieldname: 'status',
							class: !isMobile() ? 'w-24' : '',
							options: [
								{ label: '', value: '' },
								{ label: t('Pending'), value: 'Pending' },
								{ label: t('Running'), value: 'Running' },
								{ label: t('Success'), value: 'Success' },
								{ label: t('Failure'), value: 'Failure' }
							]
						},
						{
							type: 'link',
							label: t('Type'),
							fieldname: 'job_type',
							options: {
								pagetype: 'Agent Job Type',
								orderBy: 'name asc',
								pageLength: 100
							}
						}
					];
				},
				columns: [
					{
						label: t('Job Type'),
						fieldname: 'job_type',
						class: 'font-medium',
						format: jobTypeI18n
					},
					{
						label: t('Status'),
						fieldname: 'status',
						type: 'Badge',
						width: 0.5,
						format: statusI18n
					},
					{
						label: t('Site'),
						fieldname: 'site',
						width: 1.2,
						condition: () => pagetype !== 'Site'
					},
					{
						label: t('Duration'),
						fieldname: 'duration',
						width: 0.35,
						format(value, row) {
							if (row.job_id === 0 || !row.end) return;
							return duration(value);
						}
					},
					{
						label: t('Owner'),
						fieldname: 'owner'
					},
					{
						label: '',
						fieldname: 'creation',
						type: 'Timestamp',
						width: 0.5,
						align: 'right',
						format: formatTimeRelative
					}
				].filter(c => (c.condition ? c.condition() : true))
			};
		}
	}
};
</script>