import { mkdir, readFile, writeFile } from 'fs/promises';
import path from 'path';

export type LocalDevEntity =
  | 'customers'
  | 'drivers'
  | 'restaurants'
  | 'delivery-settings'
  | 'pricing-rules'
  | 'subscriptions'
  | 'ads-campaigns'
  | 'reports';

export type LocalDevRecord = Record<string, unknown> & {
  id: string;
  createdAt: string;
  updatedAt: string;
};

type LocalDevStore = Record<LocalDevEntity, LocalDevRecord[]>;

const STORE_PATH = path.join(process.cwd(), '..', '..', 'storage', 'local-dev-db.json');

const initialStore: LocalDevStore = {
  customers: [
    {
      id: 'customer-1',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      fullName: 'Camila Cliente',
      email: 'cliente@chego.app',
      phone: '5511966665555',
      document: '123.456.789-10',
      city: 'Sao Paulo',
      neighborhood: 'Vila Mariana',
      walletBalance: 118.4,
      status: 'ACTIVE',
      ltv: 486,
      repurchaseRate: 0.38,
    },
  ],
  drivers: [
    {
      id: 'driver-1',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      fullName: 'Mateus Entregas',
      phone: '5511977776666',
      document: '12345678900',
      vehiclePlate: 'CHE1G01',
      vehicleModel: 'Honda CG 160',
      pixKey: 'entregador@chego.app',
      city: 'Sao Paulo',
      status: 'ACTIVE',
      online: true,
      walletBalance: 1284,
    },
  ],
  restaurants: [
    {
      id: 'restaurant-1',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      name: 'Forno da Esquina',
      slug: 'forno-da-esquina',
      documentNumber: '12345678000199',
      ownerEmail: 'loja@chego.app',
      ownerPhone: '5511988887777',
      city: 'Sao Paulo',
      neighborhood: 'Centro',
      commissionPercentage: 18,
      serviceFeePercentage: 0,
      baseDeliveryFee: 10,
      pricePerKm: 1.5,
      sponsored: true,
      status: 'ACTIVE',
    },
  ],
  'delivery-settings': [
    {
      id: 'delivery-settings-default',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      baseFee: 6,
      pricePerKm: 2,
      minimumDeliveryFee: 7,
      maximumDeliveryFee: 40,
      platformDeliveryMargin: 0,
      peakHourMultiplier: 1.18,
      rainMultiplier: 1.22,
      lowDriverSupplyMultiplier: 1.2,
    },
  ],
  'pricing-rules': [
    {
      id: 'pricing-rule-default',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      scope: 'global',
      commissionDefault: 18,
      serviceFeeFixed: 0,
      serviceFeePercentage: 0,
      premiumCashbackPercentage: 5,
      surgeEnabled: true,
    },
  ],
  subscriptions: [
    {
      id: 'subscription-1',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      holder: 'Camila Cliente',
      plan: 'Cliente Prime',
      type: 'CUSTOMER',
      price: 29.9,
      status: 'ACTIVE',
      renewalAt: '2026-05-29',
    },
  ],
  'ads-campaigns': [
    {
      id: 'ads-1',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      campaignName: 'Burrata Premium',
      restaurantName: 'Forno da Esquina',
      placement: 'HOME_HERO',
      budget: 320,
      cpc: 1.4,
      roas: 4.8,
      status: 'ACTIVE',
    },
  ],
  reports: [
    {
      id: 'report-1',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      title: 'LTV por cidade',
      scope: 'FINANCE',
      format: 'CSV',
      period: 'last_30_days',
      status: 'READY',
    },
  ],
};

async function ensureStore() {
  await mkdir(path.dirname(STORE_PATH), { recursive: true });
  try {
    await readFile(STORE_PATH, 'utf8');
  } catch {
    await writeFile(STORE_PATH, JSON.stringify(initialStore, null, 2), 'utf8');
  }
}

async function readStore(): Promise<LocalDevStore> {
  await ensureStore();
  const content = await readFile(STORE_PATH, 'utf8');
  return JSON.parse(content) as LocalDevStore;
}

async function writeStore(store: LocalDevStore) {
  await writeFile(STORE_PATH, JSON.stringify(store, null, 2), 'utf8');
}

export function isValidEntity(value: string): value is LocalDevEntity {
  return value in initialStore;
}

export async function listRecords(entity: LocalDevEntity) {
  const store = await readStore();
  return store[entity];
}

export async function getRecord(entity: LocalDevEntity, id: string) {
  const store = await readStore();
  return store[entity].find((item) => item.id === id) ?? null;
}

export async function createRecord(entity: LocalDevEntity, payload: Record<string, unknown>) {
  const store = await readStore();
  const now = new Date().toISOString();
  const record: LocalDevRecord = {
    id: String(payload.id ?? `${entity}-${Date.now()}`),
    createdAt: now,
    updatedAt: now,
    ...payload,
  };

  store[entity].unshift(record);
  await writeStore(store);
  return record;
}

export async function updateRecord(entity: LocalDevEntity, id: string, payload: Record<string, unknown>) {
  const store = await readStore();
  const index = store[entity].findIndex((item) => item.id === id);
  if (index === -1) {
    return null;
  }

  const current = store[entity][index];
  const next = {
    ...current,
    ...payload,
    id: current.id,
    createdAt: current.createdAt,
    updatedAt: new Date().toISOString(),
  } satisfies LocalDevRecord;

  store[entity][index] = next;
  await writeStore(store);
  return next;
}

export async function deleteRecord(entity: LocalDevEntity, id: string) {
  const store = await readStore();
  const index = store[entity].findIndex((item) => item.id === id);
  if (index === -1) {
    return null;
  }

  const [removed] = store[entity].splice(index, 1);
  await writeStore(store);
  return removed;
}
