import { config } from '../config/index.js';
import logger from '../utils/logger.js';
import { observabilityService } from './observabilityService.js';
import {
    type ReconciliationSubTagRepairSummary,
    supabaseService
} from './SupabaseService.js';

export interface ReconciliationSubTagRepairContext {
    profileId: string;
    userId: string;
}

export type ReconciliationSubTagRepairResult = ReconciliationSubTagRepairSummary & {
    skippedReason?: string;
};

export class ReconciliationSubTagRepairService {
    async runProfile(ctx: ReconciliationSubTagRepairContext): Promise<ReconciliationSubTagRepairResult> {
        const dryRun = Boolean(config.RECON_SUBTAG_REPAIR_DRY_RUN);
        if (!config.ENABLE_RECON_SUBTAG_REPAIR) {
            return {
                attempted: false,
                skippedReason: 'disabled',
                scannedRows: 0,
                eligibleRows: 0,
                updatedRows: 0,
                skippedNoProfile: 0,
                skippedNoTrade: 0,
                skippedTagDisabled: 0,
                skippedAlreadyTagged: 0,
                dryRun
            };
        }

        const lookbackHours = Math.max(1, Math.floor(Number(config.RECON_SUBTAG_REPAIR_LOOKBACK_HOURS || 720)));
        const maxUpdatesPerProfile = Math.max(1, Math.floor(Number(config.RECON_SUBTAG_REPAIR_MAX_UPDATES_PER_PROFILE || 500)));

        const result = await supabaseService.repairMissingSubTagsForProfile({
            profileId: ctx.profileId,
            lookbackHours,
            maxRows: maxUpdatesPerProfile,
            dryRun
        });

        if (result.unsupported) {
            observabilityService.emitEvent({
                type: 'SYSTEM_ERROR',
                severity: 'ERROR',
                message: `Sub-tag repair skipped: orders.sub_tag column unavailable for profile ${ctx.profileId}`,
                profileId: ctx.profileId,
                userId: ctx.userId
            });
            return result;
        }

        if (result.updatedRows > 0 || result.eligibleRows > 0) {
            logger.warn('[ReconcileSubTag] Missing sub_tag repair evaluated', {
                event: 'reconciliation_subtag_repair_profile',
                profileId: ctx.profileId,
                userId: ctx.userId,
                dryRun: result.dryRun,
                scannedRows: result.scannedRows,
                eligibleRows: result.eligibleRows,
                updatedRows: result.updatedRows,
                skippedNoProfile: result.skippedNoProfile,
                skippedNoTrade: result.skippedNoTrade,
                skippedTagDisabled: result.skippedTagDisabled,
                skippedAlreadyTagged: result.skippedAlreadyTagged
            });
        }

        return result;
    }
}

export const reconciliationSubTagRepairService = new ReconciliationSubTagRepairService();
