"use server";

import * as z from "zod";

// Re-define or import the schema to validate on the server-side
// Ensure this matches the client-side schema
const applicationSchema = z.object({
  vacancyId: z.string(),
  vacancyTitle: z.string(),
  firstName: z.string().min(1, "First name is required"),
  lastName: z.string().min(1, "Last name is required"),
  email: z.string().email("Invalid email address"),
  phone: z.string().optional(),
  linkedinUrl: z.string().url("Invalid URL").optional().or(z.literal("")),
  portfolioUrl: z.string().url("Invalid URL").optional().or(z.literal("")),
  coverLetter: z.string().optional(),
  // Note: File uploads (resume) are not handled in this basic action.
  // Handling files requires FormData and different processing.
});

type ApplicationFormData = z.infer<typeof applicationSchema>;

interface ActionResult {
  success: boolean;
  message?: string;
}

export async function submitApplication(
  formData: ApplicationFormData
): Promise<ActionResult> {
  // 1. Validate data on the server
  const validatedFields = applicationSchema.safeParse(formData);

  if (!validatedFields.success) {
    console.error(
      "Server-side validation failed:",
      validatedFields.error.flatten().fieldErrors
    );
    return {
      success: false,
      message: "Invalid data provided. Please check the form.",
      // Optionally return specific field errors: errors: validatedFields.error.flatten().fieldErrors
    };
  }

  const applicationData = validatedFields.data;

  // 2. Process the application (e.g., save to database, send email)
  // For this demo, we'll just log the data.
  console.log(
    "Received application:",
    JSON.stringify(applicationData, null, 2)
  );

  // Simulate processing time
  await new Promise((resolve) => setTimeout(resolve, 1000));

  // In a real application:
  // - Save applicationData to your database (e.g., using Prisma or Directus SDK)
  // - Handle resume file upload (requires FormData, potentially upload to storage like S3/Minio)
  // - Send notification emails (to HR, to the applicant)

  // Example of error handling during processing:
  // try {
  //   await saveApplicationToDatabase(applicationData);
  //   await sendConfirmationEmail(applicationData.email);
  // } catch (error) {
  //   console.error('Failed to process application:', error);
  //   return { success: false, message: 'Failed to save application.' };
  // }

  // 3. Return success response
  return { success: true, message: "Application submitted successfully!" };
}
