import { Injectable, Inject } from "@nestjs/common";
import { Logger } from "nestjs-pino";
import { WorkflowCaseManager } from "@bff/modules/shared/workflow/index.js";
import { OpportunityResolutionService } from "@bff/integrations/salesforce/services/opportunity-resolution.service.js";

export interface CreateEligibilityCaseAddress {
  address1: string;
  address2?: string;
  city: string;
  state?: string;
  postcode: string;
  country?: string;
  /** Japanese full street address — used for duplicate detection */
  streetAddress?: string;
}

export interface CreateEligibilityCaseParams {
  sfAccountId: string;
  address: CreateEligibilityCaseAddress;
}

export interface CreateEligibilityCaseResult {
  caseId: string;
  caseNumber: string;
}

/**
 * Step: Create a Salesforce eligibility case.
 *
 * Finds or creates an Opportunity for internet eligibility,
 * then creates a notification case via WorkflowCaseManager.
 *
 * No rollback — cases are idempotent.
 */
@Injectable()
export class CreateEligibilityCaseStep {
  constructor(
    private readonly workflowCaseManager: WorkflowCaseManager,
    private readonly opportunityResolution: OpportunityResolutionService,
    @Inject(Logger) private readonly logger: Logger
  ) {}

  async execute(params: CreateEligibilityCaseParams): Promise<CreateEligibilityCaseResult> {
    const { sfAccountId, address } = params;

    // Find or create Opportunity for Internet eligibility
    const { opportunityId, wasCreated: opportunityCreated } =
      await this.opportunityResolution.findOrCreateForInternetEligibility(sfAccountId);

    // Create eligibility case via workflow manager
    await this.workflowCaseManager.notifyEligibilityCheck({
      accountId: sfAccountId,
      opportunityId,
      opportunityCreated,
      address: {
        address1: address.address1,
        ...(address.address2 ? { address2: address.address2 } : {}),
        city: address.city,
        state: address.state ?? "",
        postcode: address.postcode,
        ...(address.country ? { country: address.country } : {}),
      },
      ...(address.streetAddress ? { streetAddress: address.streetAddress } : {}),
    });

    // Generate a reference ID for the eligibility request
    const caseId = `eligibility:${sfAccountId}:${Date.now()}`;
    const caseNumber = `ELG-${Date.now().toString(36).toUpperCase()}`;

    this.logger.log({ sfAccountId, caseId, opportunityId }, "Eligibility case created");

    return { caseId, caseNumber };
  }
}
