"use server"

import { revalidatePath } from "next/cache"
import { cookies } from "next/headers"
import { api } from "@/lib/api"
import { ENDPOINTS } from "@/constants/endpoints"
import { ApiError } from "@/lib/errors"
import i18n from "@/lib/i18n";

export type ActionResult = { ok: true } | { ok: false; error: string }

async function requireSuperAdmin() {
  const cookieStore = await cookies()
  const userCookie = cookieStore.get("auth_user")?.value

  if (!userCookie) {
    return { ok: false as const, error: i18n.t('app.admin.roles.actions.text_1') }
  }

  try {
    const user = JSON.parse(decodeURIComponent(userCookie))
    if (user.role !== "super_admin" && user.role !== "SUPER_ADMIN") {
      return { ok: false as const, error: i18n.t('app.admin.roles.actions.text_2') }
    }
    return { ok: true as const }
  } catch {
    return { ok: false as const, error: i18n.t('app.admin.roles.actions.text_3') }
  }
}

function extractErrorMessage(err: unknown, fallback: string): string {
  if (err instanceof ApiError) {
    return err.message || fallback
  }
  if (err instanceof Error) {
    return err.message || fallback
  }
  return fallback
}

/* -------------------- Roles -------------------- */

export async function createRole(formData: FormData): Promise<ActionResult> {
  const auth = await requireSuperAdmin()
  if (!auth.ok) return auth

  const code = String(formData.get("code") ?? "")
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9_]/g, "_")
  const name = String(formData.get("name") ?? "").trim()
  const description = String(formData.get("description") ?? "").trim() || null

  if (!code || !name) return { ok: false, error: i18n.t('app.admin.roles.actions.text_4') }

  try {
    await api.post(ENDPOINTS.ROLES.CREATE, { code, name_ar: name, description })
    revalidatePath("/roles")
    return { ok: true }
  } catch (err: unknown) {
    return { ok: false, error: extractErrorMessage(err, i18n.t('app.admin.roles.actions.text_5')) }
  }
}

export async function updateRole(formData: FormData): Promise<ActionResult> {
  const auth = await requireSuperAdmin()
  if (!auth.ok) return auth

  const id = String(formData.get("id") ?? "")
  const name = String(formData.get("name") ?? "").trim()
  const description = String(formData.get("description") ?? "").trim() || null

  if (!id || !name) return { ok: false, error: i18n.t('app.admin.roles.actions.text_6') }

  try {
    await api.patch(ENDPOINTS.ROLES.UPDATE(id), { name_ar: name, description })
    revalidatePath("/roles")
    return { ok: true }
  } catch (err: unknown) {
    return { ok: false, error: extractErrorMessage(err, i18n.t('app.admin.roles.actions.text_7')) }
  }
}

export async function deleteRole(formData: FormData): Promise<ActionResult> {
  const auth = await requireSuperAdmin()
  if (!auth.ok) return auth

  const id = String(formData.get("id") ?? "")
  if (!id) return { ok: false, error: i18n.t('app.admin.roles.actions.text_8') }

  try {
    await api.del(ENDPOINTS.ROLES.DELETE(id))
    revalidatePath("/roles")
    return { ok: true }
  } catch (err: unknown) {
    return { ok: false, error: extractErrorMessage(err, i18n.t('app.admin.roles.actions.text_9')) }
  }
}

/* -------------------- Permissions matrix -------------------- */

export async function togglePermission(formData: FormData): Promise<ActionResult> {
  const auth = await requireSuperAdmin()
  if (!auth.ok) return auth

  const roleId = String(formData.get("role_id") ?? "")
  const module = String(formData.get("module") ?? "")
  const key = String(formData.get("key") ?? "")
  const next = formData.get("value") === "true"

  if (!roleId || !module) {
    return { ok: false, error: i18n.t('app.admin.roles.actions.text_10') }
  }

  try {
    await api.put(ENDPOINTS.ROLES.GET_BY_ID(roleId) + '/permissions', {
      module,
      permission: key,
      value: next,
    })
    revalidatePath("/roles")
    return { ok: true }
  } catch (err: unknown) {
    return { ok: false, error: extractErrorMessage(err, i18n.t('app.admin.roles.actions.text_11')) }
  }
}

export async function updateRolePermissions(roleId: string, permissionIds: string[]) {
  try {
    const endpoint = ENDPOINTS.ROLES.GET_BY_ID(roleId) + '/permissions';
    await api.post(endpoint, {
      permission_ids: permissionIds,
    });
    
    revalidatePath("/roles")
    return { ok: true }
  } catch (err: unknown) {
    if (err instanceof ApiError) return { ok: false, error: err.message }
    return { ok: false, error: i18n.t('app.admin.roles.actions.text_12') }
  }
}

/* -------------------- Admin users -------------------- */

export async function updateAdminUser(formData: FormData): Promise<ActionResult> {
  const auth = await requireSuperAdmin()
  if (!auth.ok) return auth

  const id = String(formData.get("id") ?? "")
  const full_name = String(formData.get("full_name") ?? "").trim() || null
  const role = String(formData.get("role") ?? "")
  const status = String(formData.get("status") ?? "active")

  if (!id || !role) return { ok: false, error: i18n.t('app.admin.roles.actions.text_13') }

  try {
    await api.patch('users/' + id, { full_name_ar: full_name, role, status })
    revalidatePath("/roles")
    return { ok: true }
  } catch (err: unknown) {
    return { ok: false, error: extractErrorMessage(err, i18n.t('app.admin.roles.actions.text_14')) }
  }
}

export async function setAdminUserStatus(formData: FormData): Promise<ActionResult> {
  const auth = await requireSuperAdmin()
  if (!auth.ok) return auth
  const id = String(formData.get("id") ?? "")
  const status = String(formData.get("status") ?? "")
  if (!id || !["active", "suspended"].includes(status))
    return { ok: false, error: i18n.t('app.admin.roles.actions.text_15') }

  try {
    await api.patch('users/' + id, { status })
    revalidatePath("/roles")
    return { ok: true }
  } catch (err: unknown) {
    return { ok: false, error: extractErrorMessage(err, i18n.t('app.admin.roles.actions.text_16')) }
  }
}