import { existsSync } from "node:fs";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";

export type JobSlideConfig = {
  id: string;
  imageUrl: string;
  label: string;
  title: string;
  subtitle: string;
  isActive: boolean;
  sortOrder: number;
};

export type JobApiSourceConfig = {
  id: string;
  name: string;
  sourceKey: string;
  endpoint: string;
  isActive: boolean;
  authHeader: string;
  authToken: string;
  jobPath: string;
  titleKey: string;
  companyKey: string;
  locationKey: string;
  typeKey: string;
  salaryKey: string;
  descriptionKey: string;
  applyLinkKey: string;
  postedAtKey: string;
  externalIdKey: string;
};

const DATA_DIR = path.join(process.cwd(), "data");
const SLIDES_FILE = path.join(DATA_DIR, "jobs-slides.json");
const SOURCES_FILE = path.join(DATA_DIR, "jobs-api-sources.json");

const DEFAULT_SLIDES: JobSlideConfig[] = [
  {
    id: "jobs-slide-1",
    label: "2,400+ Live Jobs",
    title: "Find Your Dream Career",
    subtitle: "Top companies in Malaysia are hiring now",
    imageUrl: "https://images.unsplash.com/photo-1521737604893-d14cc237f11d?w=1600&q=80",
    isActive: true,
    sortOrder: 0,
  },
  {
    id: "jobs-slide-2",
    label: "Remote & Hybrid Roles",
    title: "Work From Anywhere",
    subtitle: "Discover flexible opportunities that fit your lifestyle",
    imageUrl: "https://images.unsplash.com/photo-1600880292203-757bb62b4baf?w=1600&q=80",
    isActive: true,
    sortOrder: 1,
  },
];

const DEFAULT_SOURCES: JobApiSourceConfig[] = [
  {
    id: "source-remotive",
    name: "Remotive Demo",
    sourceKey: "remotive",
    endpoint: "https://remotive.com/api/remote-jobs",
    isActive: false,
    authHeader: "",
    authToken: "",
    jobPath: "jobs",
    titleKey: "title",
    companyKey: "company_name",
    locationKey: "candidate_required_location",
    typeKey: "job_type",
    salaryKey: "salary",
    descriptionKey: "description",
    applyLinkKey: "url",
    postedAtKey: "publication_date",
    externalIdKey: "id",
  },
];

async function ensureDir() {
  await mkdir(DATA_DIR, { recursive: true });
}

async function readJsonFile<T>(filePath: string, fallback: T): Promise<T> {
  await ensureDir();
  if (!existsSync(filePath)) {
    await writeFile(filePath, JSON.stringify(fallback, null, 2), "utf-8");
    return fallback;
  }

  try {
    const raw = await readFile(filePath, "utf-8");
    return JSON.parse(raw) as T;
  } catch {
    await writeFile(filePath, JSON.stringify(fallback, null, 2), "utf-8");
    return fallback;
  }
}

async function writeJsonFile<T>(filePath: string, data: T): Promise<void> {
  await ensureDir();
  await writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
}

export async function readJobSlidesConfig(): Promise<JobSlideConfig[]> {
  const slides = await readJsonFile<JobSlideConfig[]>(SLIDES_FILE, DEFAULT_SLIDES);
  return slides.sort((a, b) => a.sortOrder - b.sortOrder);
}

export async function writeJobSlidesConfig(slides: JobSlideConfig[]): Promise<void> {
  await writeJsonFile(SLIDES_FILE, slides);
}

export async function readJobApiSourcesConfig(): Promise<JobApiSourceConfig[]> {
  return readJsonFile<JobApiSourceConfig[]>(SOURCES_FILE, DEFAULT_SOURCES);
}

export async function writeJobApiSourcesConfig(sources: JobApiSourceConfig[]): Promise<void> {
  await writeJsonFile(SOURCES_FILE, sources);
}
