import type { Context } from "hono";
import { error, success } from "@/lib/response";
import { logError } from "@/lib/logger";
import { sql } from "kysely";
import { StrapiGet } from "@/strapi";
import pg from "pg";
import fs from "fs";
import path from "path";


const UNIT_TYPES = ["Imperial Unit", "Fractional Unit"];

export const ResortController = (ctx: Context) => {
  const db = ctx.get("datastore");

  return {
    async ListResorts() {
      try {
        const q = ctx.req.query();
        const page = Math.max(1, parseInt(q.page ?? "1", 10));
        const limit = Math.min(100, Math.max(1, parseInt(q.limit ?? "20", 10)));
        const offset = (page - 1) * limit;
        const search = q.search?.trim() ?? "";
        const grade = q.grade?.trim() ?? "";
        const isActive = q.is_active?.trim() ?? "";

        let query = db
          .selectFrom("resorts" as any)
          .selectAll()
          .orderBy("created_at", "desc");

        if (search) {
          query = query.where("name", "ilike", `%${search}%`);
        }
        if (grade) {
          query = query.where("grade", "=", grade);
        }
        if (isActive !== "") {
          query = query.where("is_active", "=", isActive === "true");
        }

        const items = await query.limit(limit).offset(offset).execute();

        let countQuery = db
          .selectFrom("resorts" as any)
          .select((eb: any) => eb.fn.count("id").as("count"));
        if (search) {
          countQuery = countQuery.where("name", "ilike", `%${search}%`);
        }
        if (grade) {
          countQuery = countQuery.where("grade", "=", grade);
        }
        if (isActive !== "") {
          countQuery = countQuery.where("is_active", "=", isActive === "true");
        }
        const countResult = await countQuery.executeTakeFirst();
        const total = Number(countResult?.count ?? 0);

        return success(ctx, { items, total, page, limit });
      } catch (err: any) {
        logError("[Resorts] ListResorts:", err);
        return error(ctx, err?.message ?? "Failed to list resorts", 500);
      }
    },

    async GetResort() {
      try {
        const { id } = ctx.req.param() as { id: string };

        const resort = await db
          .selectFrom("resorts" as any)
          .selectAll()
          .where("id", "=", id)
          .executeTakeFirst();

        if (!resort) return error(ctx, "Resort not found", 404);

        const units = await db
          .selectFrom("resort_units" as any)
          .selectAll()
          .where("resort_id", "=", id)
          .orderBy("sort_order", "asc")
          .execute();

        return success(ctx, { ...resort, units });
      } catch (err: any) {
        logError("[Resorts] GetResort:", err);
        return error(ctx, err?.message ?? "Failed to get resort", 500);
      }
    },

    async CreateResort() {
      try {
        const body = await ctx.req.json();

        if (!body.name?.trim()) return error(ctx, "name is required", 400);

        const adminEmail = ctx.get("email") ?? ctx.get("adminEmail") ?? null;

        const resort = await db
          .insertInto("resorts" as any)
          .values({
            name: body.name.trim(),
            code: body.code?.trim() ?? null,
            description: body.description ?? null,
            address: body.address?.trim() ?? null,
            country: body.country?.trim() ?? null,
            state_region: body.state_region?.trim() ?? null,
            phone: body.phone?.trim() ?? null,
            email: body.email?.trim() ?? null,
            website_url: body.website_url?.trim() ?? null,
            cover_image: body.cover_image ?? null,
            gallery_images: body.gallery_images ?? [],
            thumbnail: body.thumbnail ?? null,
            map_image: body.map_image ?? null,
            mobile_banner: body.mobile_banner ?? null,
            resort_logo: body.resort_logo ?? null,
            grade: body.grade ?? null,
            is_active: body.is_active ?? true,
            adult_age_from: body.adult_age_from ?? null,
            adult_age_to: body.adult_age_to ?? null,
            children_age_from: body.children_age_from ?? null,
            children_age_to: body.children_age_to ?? null,
            infant_age_from: body.infant_age_from ?? null,
            infant_age_to: body.infant_age_to ?? null,
            peak_periods: JSON.stringify(body.peak_periods ?? []),
            blackout_periods: JSON.stringify(body.blackout_periods ?? []),
            open_close_periods: JSON.stringify(body.open_close_periods ?? []),
            seasons: JSON.stringify(body.seasons ?? []),
            vpid: JSON.stringify(body.vpid ?? []),
            gl_code: body.gl_code ?? null,
            gl_code_curated: body.gl_code_curated ?? null,
            gl_used: body.gl_used !== undefined && body.gl_used !== null ? Number(body.gl_used) : null,
            gl_rate_plans: JSON.stringify(body.gl_rate_plans ?? []),
            gl_push_booking: body.gl_push_booking ?? false,
            gl_push_booking_rate_plan: body.gl_push_booking_rate_plan ?? null,
            gl_push_booking_map: body.gl_push_booking_map ?? false,
            roles_denied: JSON.stringify(body.roles_denied ?? []),
            created_by: adminEmail,
            updated_by: adminEmail,
          })
          .returningAll()
          .executeTakeFirstOrThrow();

        if (Array.isArray(body.units) && body.units.length > 0) {
          await db
            .insertInto("resort_units" as any)
            .values(
              body.units.map((u: any, idx: number) => ({
                resort_id: resort.id,
                unit_name: u.unit_name,
                unit_vp_code: u.unit_vp_code,
                unit_type: u.unit_type ?? null,
                total_occupancy: u.total_occupancy ?? null,
                adult_occupancy: u.adult_occupancy ?? null,
                children_occupancy: u.children_occupancy ?? null,
                child_occupancy: u.child_occupancy ?? null,
                is_active: u.is_active ?? true,
                eligible_for_hot_deals: u.eligible_for_hot_deals ?? true,
                eligible_for_exclusive_discovery: u.eligible_for_exclusive_discovery ?? true,
                sort_order: u.sort_order ?? idx,
                description: u.description ?? null,
                featured_image: u.featured_image ?? null,
                images: u.images ?? [],
                roles: typeof u.roles === "string" ? u.roles : JSON.stringify(u.roles ?? []),
                unit_points: typeof u.unit_points === "string" ? u.unit_points : JSON.stringify(u.unit_points ?? {}),
              })),
            )
            .execute();
        }

        const units = await db
          .selectFrom("resort_units" as any)
          .selectAll()
          .where("resort_id", "=", resort.id)
          .orderBy("sort_order", "asc")
          .execute();

        return success(ctx, { ...resort, units }, "Resort created", 201);
      } catch (err: any) {
        logError("[Resorts] CreateResort:", err);
        return error(ctx, err?.message ?? "Failed to create resort", 500);
      }
    },

    async UpdateResort() {
      try {
        const { id } = ctx.req.param() as { id: string };
        const body = await ctx.req.json();

        const existing = await db
          .selectFrom("resorts" as any)
          .select(["id"])
          .where("id", "=", id)
          .executeTakeFirst();

        if (!existing) return error(ctx, "Resort not found", 404);

        if (body.name !== undefined && !body.name?.trim()) {
          return error(ctx, "name cannot be empty", 400);
        }

        const adminEmail = ctx.get("email") ?? ctx.get("adminEmail") ?? null;

        const updates: Record<string, any> = { updated_at: new Date(), updated_by: adminEmail };

        const scalarFields = [
          "name", "code", "description", "address", "country", "state_region",
          "phone", "email", "website_url", "cover_image", "gallery_images",
          "grade", "is_active", "adult_age_from", "adult_age_to",
          "children_age_from", "children_age_to", "infant_age_from", "infant_age_to",
          "thumbnail", "map_image", "mobile_banner", "resort_logo",
          "gl_code", "gl_code_curated", "gl_used", "gl_push_booking",
          "gl_push_booking_rate_plan", "gl_push_booking_map",
        ];
        for (const f of scalarFields) {
          if (body[f] !== undefined) updates[f] = body[f];
        }

        const jsonFields = [
          "peak_periods", "blackout_periods", "open_close_periods", "seasons",
          "vpid", "gl_rate_plans", "roles_denied"
        ];
        for (const f of jsonFields) {
          if (body[f] !== undefined) updates[f] = JSON.stringify(body[f]);
        }

        const resort = await db
          .updateTable("resorts" as any)
          .set(updates)
          .where("id", "=", id)
          .returningAll()
          .executeTakeFirstOrThrow();

        if (Array.isArray(body.units)) {
          await db.deleteFrom("resort_units" as any).where("resort_id", "=", id).execute();
          if (body.units.length > 0) {
            await db
              .insertInto("resort_units" as any)
              .values(
                body.units.map((u: any, idx: number) => ({
                  id: u.id ?? undefined,
                  resort_id: id,
                  unit_name: u.unit_name,
                  unit_vp_code: u.unit_vp_code,
                  unit_type: u.unit_type ?? null,
                  total_occupancy: u.total_occupancy ?? null,
                  adult_occupancy: u.adult_occupancy ?? null,
                  children_occupancy: u.children_occupancy ?? null,
                  child_occupancy: u.child_occupancy ?? null,
                  is_active: u.is_active ?? true,
                  eligible_for_hot_deals: u.eligible_for_hot_deals ?? true,
                  eligible_for_exclusive_discovery: u.eligible_for_exclusive_discovery ?? true,
                  sort_order: u.sort_order ?? idx,
                  description: u.description ?? null,
                  featured_image: u.featured_image ?? null,
                  images: u.images ?? [],
                  roles: typeof u.roles === "string" ? u.roles : JSON.stringify(u.roles ?? []),
                  unit_points: typeof u.unit_points === "string" ? u.unit_points : JSON.stringify(u.unit_points ?? {}),
                })),
              )
              .execute();
          }
        }

        const units = await db
          .selectFrom("resort_units" as any)
          .selectAll()
          .where("resort_id", "=", id)
          .orderBy("sort_order", "asc")
          .execute();

        return success(ctx, { ...resort, units }, "Resort updated");
      } catch (err: any) {
        logError("[Resorts] UpdateResort:", err);
        return error(ctx, err?.message ?? "Failed to update resort", 500);
      }
    },

    async DeleteResort() {
      try {
        const { id } = ctx.req.param() as { id: string };

        const existing = await db
          .selectFrom("resorts" as any)
          .select(["id"])
          .where("id", "=", id)
          .executeTakeFirst();

        if (!existing) return error(ctx, "Resort not found", 404);

        await db.deleteFrom("resorts" as any).where("id", "=", id).execute();

        return success(ctx, null, "Resort deleted");
      } catch (err: any) {
        logError("[Resorts] DeleteResort:", err);
        return error(ctx, err?.message ?? "Failed to delete resort", 500);
      }
    },

    async ListResortUnits() {
      try {
        const { id } = ctx.req.param() as { id: string };
        const units = await db
          .selectFrom("resort_units" as any)
          .selectAll()
          .where("resort_id", "=", id)
          .orderBy("sort_order", "asc")
          .execute();
        return success(ctx, units);
      } catch (err: any) {
        logError("[Resorts] ListResortUnits:", err);
        return error(ctx, err?.message ?? "Failed to list units", 500);
      }
    },

    async CreateResortUnit() {
      try {
        const { id } = ctx.req.param() as { id: string };
        const body = await ctx.req.json();

        if (!body.unit_name?.trim()) return error(ctx, "unit_name is required", 400);
        if (!body.unit_vp_code?.trim()) return error(ctx, "unit_vp_code is required", 400);

        const countRes = await db
          .selectFrom("resort_units" as any)
          .select((eb: any) => eb.fn.count("id").as("count"))
          .where("resort_id", "=", id)
          .executeTakeFirst();
        const sortOrder = Number(countRes?.count ?? 0);

        const unit = await db
          .insertInto("resort_units" as any)
          .values({
            resort_id: id,
            unit_name: body.unit_name.trim(),
            unit_vp_code: body.unit_vp_code.trim(),
            unit_type: body.unit_type ?? null,
            total_occupancy: body.total_occupancy ?? null,
            adult_occupancy: body.adult_occupancy ?? null,
            children_occupancy: body.children_occupancy ?? null,
            child_occupancy: body.child_occupancy ?? null,
            is_active: body.is_active ?? true,
            eligible_for_hot_deals: body.eligible_for_hot_deals ?? true,
            eligible_for_exclusive_discovery: body.eligible_for_exclusive_discovery ?? true,
            sort_order: body.sort_order ?? sortOrder,
            description: body.description ?? null,
            featured_image: body.featured_image ?? null,
            images: body.images ?? [],
            roles: typeof body.roles === "string" ? body.roles : JSON.stringify(body.roles ?? []),
            unit_points: typeof body.unit_points === "string" ? body.unit_points : JSON.stringify(body.unit_points ?? {}),
          })
          .returningAll()
          .executeTakeFirstOrThrow();

        return success(ctx, unit, "Unit created", 201);
      } catch (err: any) {
        logError("[Resorts] CreateResortUnit:", err);
        return error(ctx, err?.message ?? "Failed to create unit", 500);
      }
    },

    async UpdateResortUnit() {
      try {
        const { id, unitId } = ctx.req.param() as { id: string; unitId: string };
        const body = await ctx.req.json();

        const existing = await db
          .selectFrom("resort_units" as any)
          .select(["id"])
          .where("id", "=", unitId)
          .where("resort_id", "=", id)
          .executeTakeFirst();

        if (!existing) return error(ctx, "Unit not found", 404);

        const updates: Record<string, any> = { updated_at: new Date() };
        const fields = [
          "unit_name", "unit_vp_code", "unit_type", "total_occupancy",
          "adult_occupancy", "children_occupancy", "child_occupancy",
          "is_active", "eligible_for_hot_deals", "eligible_for_exclusive_discovery",
          "sort_order", "description", "featured_image", "images",
        ];
        for (const f of fields) {
          if (body[f] !== undefined) updates[f] = body[f];
        }

        const jsonFields = ["roles", "unit_points"];
        for (const f of jsonFields) {
          if (body[f] !== undefined) {
            updates[f] = typeof body[f] === "string" ? body[f] : JSON.stringify(body[f]);
          }
        }

        const unit = await db
          .updateTable("resort_units" as any)
          .set(updates)
          .where("id", "=", unitId)
          .returningAll()
          .executeTakeFirstOrThrow();

        return success(ctx, unit, "Unit updated");
      } catch (err: any) {
        logError("[Resorts] UpdateResortUnit:", err);
        return error(ctx, err?.message ?? "Failed to update unit", 500);
      }
    },

    async DeleteResortUnit() {
      try {
        const { id, unitId } = ctx.req.param() as { id: string; unitId: string };

        const existing = await db
          .selectFrom("resort_units" as any)
          .select(["id"])
          .where("id", "=", unitId)
          .where("resort_id", "=", id)
          .executeTakeFirst();

        if (!existing) return error(ctx, "Unit not found", 404);

        await db
          .deleteFrom("resort_units" as any)
          .where("id", "=", unitId)
          .execute();

        return success(ctx, null, "Unit deleted");
      } catch (err: any) {
        logError("[Resorts] DeleteResortUnit:", err);
        return error(ctx, err?.message ?? "Failed to delete unit", 500);
      }
    },

    async GetUnitTypes() {
      return success(ctx, UNIT_TYPES);
    },

    async GetEligibleUnits() {
      try {
        const { id } = ctx.req.param() as { id: string };
        const offerType = ctx.req.query("offerType") ?? "";

        let query = db
          .selectFrom("resort_units" as any)
          .selectAll()
          .where("resort_id", "=", id)
          .orderBy("sort_order", "asc");

        const units = await query.execute();

        const result = units.map((u: any) => ({
          ...u,
          default_eligible:
            offerType === "HOT_DEAL"
              ? u.eligible_for_hot_deals
              : offerType === "EXCLUSIVE_DISCOVERY"
              ? u.eligible_for_exclusive_discovery
              : true,
        }));

        return success(ctx, result);
      } catch (err: any) {
        logError("[Resorts] GetEligibleUnits:", err);
        return error(ctx, err?.message ?? "Failed to get eligible units", 500);
      }
    },

    async SyncResorts() {
      const strapiHost = process.env.STRAPI_DATABASE_HOST;
      if (!strapiHost) {
        return error(ctx, "Strapi database configuration (STRAPI_DATABASE_HOST) is not set in .env", 400);
      }

      const client = new pg.Client({
        host: strapiHost,
        port: Number(process.env.STRAPI_DATABASE_PORT || 5432),
        database: process.env.STRAPI_DATABASE_NAME || "karmadb",
        user: process.env.STRAPI_DATABASE_USER || "db_admin",
        password: process.env.STRAPI_DATABASE_PWD,
        ssl: strapiHost !== "localhost" && strapiHost !== "127.0.0.1" ? { rejectUnauthorized: false } : undefined,
      });

      try {
        await client.connect();

        // 1. Fetch all resorts with 'resort-components.property-type' component
        const resortsQuery = await client.query(`
          SELECT DISTINCT r.id, r.name, r.resort_code, r.slug, r.long_description, r.short_description, r.display_address
          FROM resorts r
          JOIN resorts_cmps rc ON rc.entity_id = r.id
          WHERE rc.component_type = 'resort-components.property-type'
        `);

        const strapiResorts = resortsQuery.rows;
        let syncedCount = 0;

        for (const sr of strapiResorts) {
          const code = sr.resort_code || sr.slug;
          if (!code) continue;

          // 2. Get Country
          const countryRes = await client.query(`
            SELECT c.country
            FROM resorts_country_lnk rcl
            JOIN countries c ON c.id = rcl.country_id
            WHERE rcl.resort_id = $1
            LIMIT 1
          `, [sr.id]);
          const country = countryRes.rows[0]?.country || null;

          // 3. Get Media (featuredImage, thumbnail, mapImage, mobileBanner)
          const mediaRes = await client.query(`
            SELECT frm.field, f.url
            FROM files_related_mph frm
            JOIN files f ON f.id = frm.file_id
            WHERE frm.related_id = $1 AND frm.related_type = 'api::resort.resort'
          `, [sr.id]);

          let featuredImage: string | null = null;
          let thumbnail: string | null = null;
          let mapImage: string | null = null;
          let mobileBanner: string | null = null;

          mediaRes.rows.forEach(row => {
            if (row.field === 'featuredImage') featuredImage = row.url;
            else if (row.field === 'thumbnail') thumbnail = row.url;
            else if (row.field === 'mapImage') mapImage = row.url;
            else if (row.field === 'mobileBanner') mobileBanner = row.url;
          });

          // 4. Get Gallery Images
          const galleryRes = await client.query(`
            SELECT f.url
            FROM resorts_cmps rc
            JOIN files_related_mph frm ON frm.related_id = rc.cmp_id AND frm.related_type = 'shared.gallery'
            JOIN files f ON f.id = frm.file_id
            WHERE rc.entity_id = $1 AND rc.component_type = 'shared.gallery' AND frm.field = 'gallery'
          `, [sr.id]);
          const galleryImages = galleryRes.rows.map(row => row.url);

          const coverImage = featuredImage || galleryImages[0] || null;

          // Check if resort exists by code or name in the local database
          let existingResort = await db
            .selectFrom("resorts" as any)
            .selectAll()
            .where("code", "=", code)
            .executeTakeFirst();

          if (!existingResort) {
            existingResort = await db
              .selectFrom("resorts" as any)
              .selectAll()
              .where("name", "ilike", sr.name)
              .executeTakeFirst();
          }

          const resortPayload: Record<string, any> = {
            name: sr.name,
            code: code,
            description: sr.long_description || sr.short_description || null,
            address: sr.display_address || null,
            country: country,
            cover_image: coverImage,
            gallery_images: galleryImages,
            thumbnail: thumbnail,
            map_image: mapImage,
            mobile_banner: mobileBanner,
            resort_logo: featuredImage,
            is_active: true,
            updated_at: new Date(),
          };

          let resortId: string;

          if (existingResort) {
            resortId = existingResort.id;
            await db
              .updateTable("resorts" as any)
              .set(resortPayload)
              .where("id", "=", resortId)
              .execute();
          } else {
            resortPayload.created_at = new Date();
            const inserted = await db
              .insertInto("resorts" as any)
              .values(resortPayload)
              .returning("id")
              .executeTakeFirstOrThrow();
            resortId = inserted.id;
          }

          // 5. Sync resort units/accommodations
          const unitsRes = await client.query(`
            SELECT ut.id, ut.unit_code, ut.unit_name, ut.description
            FROM resorts_cmps rc
            JOIN components_resorts_property_types_cmps ptc ON ptc.entity_id = rc.cmp_id AND ptc.component_type = 'resort-components.unit-type'
            JOIN components_resorts_unit_types ut ON ut.id = ptc.cmp_id
            WHERE rc.entity_id = $1 AND rc.component_type = 'resort-components.property-type'
          `, [sr.id]);

          for (const ut of unitsRes.rows) {
            if (!ut.unit_code) continue;

            // Get Unit Media
            const unitMediaRes = await client.query(`
              SELECT frm.field, f.url
              FROM files_related_mph frm
              JOIN files f ON f.id = frm.file_id
              WHERE frm.related_id = $1 AND frm.related_type = 'resort-components.unit-type'
            `, [ut.id]);

            const unitFeaturedImage = unitMediaRes.rows.find(row => row.field === 'featuredImage')?.url || null;
            const unitImages = unitMediaRes.rows.filter(row => row.field === 'images').map(row => row.url);

            const unitPayload: Record<string, any> = {
              unit_name: ut.unit_name || ut.unit_code,
              unit_vp_code: ut.unit_code,
              description: ut.description || null,
              featured_image: unitFeaturedImage,
              images: unitImages,
              is_active: true,
              updated_at: new Date(),
            };

            const existingUnit = await db
              .selectFrom("resort_units" as any)
              .select(["id"])
              .where("resort_id", "=", resortId)
              .where("unit_vp_code", "=", ut.unit_code)
              .executeTakeFirst();

            if (existingUnit) {
              await db
                .updateTable("resort_units" as any)
                .set(unitPayload)
                .where("id", "=", existingUnit.id)
                .execute();
            } else {
              unitPayload.resort_id = resortId;
              unitPayload.created_at = new Date();
              await db
                .insertInto("resort_units" as any)
                .values(unitPayload)
                .execute();
            }
          }

          syncedCount++;
        }

        return success(ctx, { synced: syncedCount }, `Successfully synced ${syncedCount} resorts`);
      } catch (err: any) {
        logError("[Resorts] SyncResorts:", err);
        return error(ctx, err?.message || "Failed to sync resorts", 500);
      } finally {
        await client.end();
      }
    },

    async SyncJsonConfig() {
      try {
        const jsonPath = path.join(process.cwd(), "resort.json");
        if (!fs.existsSync(jsonPath)) {
          return error(ctx, `resort.json file not found at ${jsonPath}`, 404);
        }

        const rawData = fs.readFileSync(jsonPath, "utf8");
        const config = JSON.parse(rawData);

        let updatedResorts = 0;
        let updatedUnits = 0;

        for (const resortName of Object.keys(config)) {
          const entry = config[resortName];
          const entryCode = entry.code;

          // Find resort by name or code
          let dbResort = await db
            .selectFrom("resorts" as any)
            .selectAll()
            .where("code", "=", entryCode)
            .executeTakeFirst();

          if (!dbResort) {
            dbResort = await db
              .selectFrom("resorts" as any)
              .selectAll()
              .where("name", "ilike", resortName)
              .executeTakeFirst();
          }

          if (!dbResort) continue;

          const resortId = dbResort.id;

          // Update resort fields
          await db
            .updateTable("resorts" as any)
            .set({
              vpid: JSON.stringify(entry.vpid ?? []),
              gl_code: entry.gl_code ?? null,
              gl_code_curated: entry.gl_code_curated ?? null,
              gl_used: entry.gl_used !== undefined && entry.gl_used !== null ? Number(entry.gl_used) : null,
              gl_rate_plans: JSON.stringify(entry.gl_rate_plans ?? []),
              gl_push_booking: entry.gl_push_booking ?? false,
              gl_push_booking_rate_plan: entry.gl_push_booking_rate_plan ?? null,
              gl_push_booking_map: entry.gl_push_booking_map ?? false,
              roles_denied: JSON.stringify(entry.roles_denied ?? []),
              updated_at: new Date(),
            })
            .where("id", "=", resortId)
            .execute();

          updatedResorts++;

          // Update units
          if (entry.units && typeof entry.units === "object") {
            const dbUnits = await db
              .selectFrom("resort_units" as any)
              .selectAll()
              .where("resort_id", "=", resortId)
              .execute();

            for (const dbUnit of dbUnits) {
              // Find matching unit in entry.units
              let jsonUnit: any = null;
              for (const key of Object.keys(entry.units)) {
                const item = entry.units[key];
                if (item.unit_code === dbUnit.unit_vp_code || key === dbUnit.unit_vp_code) {
                  jsonUnit = item;
                  break;
                }
              }

              if (jsonUnit) {
                await db
                  .updateTable("resort_units" as any)
                  .set({
                    roles: JSON.stringify(jsonUnit.roles ?? []),
                    unit_points: JSON.stringify(jsonUnit.unit_points ?? {}),
                    updated_at: new Date(),
                  })
                  .where("id", "=", dbUnit.id)
                  .execute();

                updatedUnits++;
              }
            }
          }
        }

        return success(ctx, { updatedResorts, updatedUnits }, `Successfully imported configurations from resort.json: ${updatedResorts} resorts and ${updatedUnits} units updated.`);
      } catch (err: any) {
        logError("[Resorts] SyncJsonConfig:", err);
        return error(ctx, err?.message || "Failed to sync configurations from resort.json", 500);
      }
    },
  };
};
