"use server";
import { prisma } from "@/lib/prisma";
import { revalidatePath } from "next/cache";
import { auth } from "@/auth";
import { logSystemAction } from "./system-log";

export async function getBrands() {
  try {
    const brands = await prisma.brand.findMany({ 
      where: { isActive: true }, 
      include: { 
        country: { include: { flagMedia: true } }, 
        logoMedia: true,
        createdBy: { select: { fullName: true, phone: true } },
        updatedBy: { select: { fullName: true, phone: true } }
      },
      orderBy: { name: "asc" } 
    });
    return { success: true, brands };
  } catch { return { success: true, brands: [] }; }
}

export async function createBrand(data: any) {
  try {
    const session = await auth();
    const userId = session?.user?.id;

    const slug = data.slug || data.name.toLowerCase().replace(/\s+/g, "-").replace(/[^\w\-]/g, "") + "-" + Date.now();
    const brand = await prisma.brand.create({ 
      data: { 
        name: data.name, 
        slug, 
        description: data.description || null, 
        websiteUrl: data.websiteUrl || null,
        seoTitle: data.seoTitle || null,
        seoDescription: data.seoDescription || null,
        seoKeywords: data.seoKeywords || null,
        countryId: data.countryId || null,
        logoMediaId: data.mediaId || null,
        syncStatus: 1,
        createdById: userId,
        updatedById: userId,
      } 
    });
    
    if (userId) {
      await logSystemAction("CREATE_BRAND", "Brand", brand.id, `ایجاد برند: ${brand.name}`);
    }
    
    revalidatePath("/admin/brands");
    return { success: true, brand: await prisma.brand.findUnique({ where: { id: brand.id }, include: { country: { include: { flagMedia: true } }, logoMedia: true } }) };
  } catch (e: any) { return { success: false, error: e.message }; }
}

export async function updateBrand(id: string, data: any) {
  try {
    const session = await auth();
    const userId = session?.user?.id;

    const brand = await prisma.brand.update({ 
      where: { id }, 
      data: { 
        name: data.name, 
        slug: data.slug || undefined,
        description: data.description || null,
        websiteUrl: data.websiteUrl || null,
        seoTitle: data.seoTitle || null,
        seoDescription: data.seoDescription || null,
        seoKeywords: data.seoKeywords || null,
        countryId: data.countryId || null,
        logoMediaId: data.mediaId || null,
        updatedById: userId,
      } 
    });
    
    if (userId) {
      await logSystemAction("UPDATE_BRAND", "Brand", brand.id, `ویرایش برند: ${brand.name}`);
    }
    
    revalidatePath("/admin/brands");
    return { success: true, brand: await prisma.brand.findUnique({ where: { id }, include: { country: { include: { flagMedia: true } }, logoMedia: true } }) };
  } catch (e: any) { return { success: false, error: e.message }; }
}

export async function deleteBrand(id: string) {
  try {
    await prisma.brand.delete({ where: { id } });
    revalidatePath("/admin/brands");
    return { success: true };
  } catch { return { success: false, error: "این برند دارای محصول است." }; }
}

export async function getCountries() {
  try {
    const countries = await prisma.country.findMany({ 
        orderBy: { name: "asc" },
        include: { flagMedia: true }
    });
    return { success: true, countries: countries.map(c => ({ ...c, media: c.flagMedia })) };
  } catch { return { success: true, countries: [] }; }
}

export async function createCountry(data: { name: string; mediaId?: string }) {
  try {
    const country = await prisma.country.create({
      data: {
        name: data.name,
        flagMediaId: data.mediaId || null,
      }
    });
    revalidatePath("/admin/brands");
    return { success: true, country };
  } catch (e: any) {
    return { success: false, error: e.message };
  }
}
