// services/careerService.ts
export interface ApiJob {
  id: number;
  title: string;
  department: string;
  location: string;
  type: string;
  experience: string;
  salary: string;
  description: string;
  requirements: string[];
  responsibilities: string[];
  isActive: boolean;
  createdDate?: string;
  updatedDate?: string;
}

export interface Job {
  id: string;
  title: string;
  department: string;
  location: string;
  type: string;
  experience: string;
  salary: string;
  description: string;
  requirements: string[];
  responsibilities: string[];
}

export interface JobApplicationData {
  jobId: number;
  fullName: string;
  email: string;
  phone: string;
  experience: string;
  coverLetter?: string;
  resumeUrl?: string;
}

class CareerService {
  private apiBaseUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';

  async getActiveJobs(): Promise<Job[]> {
    try {
      const response = await fetch(`${this.apiBaseUrl}/api/jobs/active`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const apiJobs: ApiJob[] = await response.json();
      return this.transformApiJobsToJobs(apiJobs);
    } catch (error) {
      console.error('Error fetching jobs:', error);
      return this.getFallbackJobs(); // Return fallback data if API fails
    }
  }

  async getJobById(id: number): Promise<Job | null> {
    try {
      const response = await fetch(`${this.apiBaseUrl}/api/jobs/${id}`);
      if (!response.ok) {
        if (response.status === 404) {
          return null;
        }
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const apiJob: ApiJob = await response.json();
      return this.transformApiJobToJob(apiJob);
    } catch (error) {
      console.error(`Error fetching job ${id}:`, error);
      return null;
    }
  }

  async submitApplication(applicationData: JobApplicationData): Promise<boolean> {
    try {
      const response = await fetch(`${this.apiBaseUrl}/api/job-applications`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(applicationData),
      });
      
      return response.ok;
    } catch (error) {
      console.error('Error submitting application:', error);
      return false;
    }
  }

  private transformApiJobsToJobs(apiJobs: ApiJob[]): Job[] {
    return apiJobs.map(apiJob => this.transformApiJobToJob(apiJob));
  }

  private transformApiJobToJob(apiJob: ApiJob): Job {
    return {
      id: apiJob.id.toString(),
      title: apiJob.title,
      department: apiJob.department,
      location: apiJob.location,
      type: apiJob.type,
      experience: apiJob.experience,
      salary: apiJob.salary,
      description: apiJob.description,
      requirements: apiJob.requirements || [],
      responsibilities: apiJob.responsibilities || []
    };
  }

  private getFallbackJobs(): Job[] {
    // Return the original hardcoded jobs as fallback
    return [
      {
        id: 'trauma-registrar',
        title: 'Trauma Registrar',
        department: 'Trauma Surgery',
        location: 'Vellore, India',
        type: 'Rotational',
        experience: 'MBBS + MS preferred',
        salary: 'As per hospital norms',
        description: 'Join our trauma surgery department as a registrar. Open year-round position with rotational duties in emergency trauma care.',
        requirements: [
          'MBBS degree required',
          'MS qualification preferred',
          'Experience in emergency medicine',
          'Ability to work in high-pressure environments'
        ],
        responsibilities: [
          'Manage trauma cases in emergency situations',
          'Assist in trauma surgeries',
          'Participate in rotational duties',
          'Maintain patient records and documentation'
        ]
      },
      {
        id: 'trauma-nurse-coordinator',
        title: 'Trauma Nurse Coordinator',
        department: 'Trauma Surgery',
        location: 'Vellore, India',
        type: 'Full-time',
        experience: 'BSc Nursing + ATCN or 2 years ICU',
        salary: 'As per hospital norms',
        description: 'Coordinate trauma nursing activities and ensure quality patient care in our trauma unit.',
        requirements: [
          'BSc Nursing degree required',
          'ATCN certification OR 2 years ICU experience',
          'Strong coordination and leadership skills',
          'Knowledge of trauma protocols'
        ],
        responsibilities: [
          'Coordinate trauma nursing activities',
          'Ensure quality patient care standards',
          'Train and supervise nursing staff',
          'Maintain trauma unit protocols'
        ]
      },
      {
        id: 'clinical-research-fellow',
        title: 'Clinical Research Fellow',
        department: 'Trauma Research',
        location: 'Vellore, India',
        type: 'Contract (1 year)',
        experience: 'Research background preferred',
        salary: 'Fellowship stipend',
        description: '1-year contract position for trauma study work. Ideal for those interested in clinical research in trauma medicine.',
        requirements: [
          'Medical degree or related field',
          'Interest in clinical research',
          'Data analysis skills',
          'Good written and verbal communication'
        ],
        responsibilities: [
          'Conduct trauma-related clinical studies',
          'Collect and analyze research data',
          'Prepare research reports and publications',
          'Collaborate with research team'
        ]
      },
      {
        id: 'short-term-observer',
        title: 'Short-Term Observer',
        department: 'Trauma Surgery',
        location: 'Vellore, India',
        type: 'Observership (4-8 weeks)',
        experience: 'Junior residents',
        salary: 'Observership program',
        description: '4-8 week observership slots for junior residents. Apply 2 months ahead for this learning opportunity.',
        requirements: [
          'Junior resident status',
          'Interest in trauma surgery',
          'Apply 2 months in advance',
          'Valid medical credentials'
        ],
        responsibilities: [
          'Observe trauma surgery procedures',
          'Learn trauma management protocols',
          'Attend clinical rounds and discussions',
          'Prepare observership reports'
        ]
      }
    ];
  }
}

export const careerService = new CareerService();