import fs from 'fs';
import path from 'path';

const DATA_DIR = path.join(process.cwd(), 'data');

function ensureDataDir() {
  if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
}

function readJSON<T>(filename: string, defaultValue: T): T {
  ensureDataDir();
  const filepath = path.join(DATA_DIR, filename);
  if (!fs.existsSync(filepath)) return defaultValue;
  try {
    return JSON.parse(fs.readFileSync(filepath, 'utf-8')) as T;
  } catch {
    return defaultValue;
  }
}

function writeJSON<T>(filename: string, data: T): void {
  ensureDataDir();
  const filepath = path.join(DATA_DIR, filename);
  fs.writeFileSync(filepath, JSON.stringify(data, null, 2));
}

// ===== ORDERS =====
export interface Order {
  id: string;
  userId: string;
  customerName: string;
  phone: string;
  email: string;
  address: { area: string; block: string; street: string; building: string; notes?: string };
  items: { id: string; name: string; nameAr: string; price: number; quantity: number; image?: string }[];
  subtotal: number;
  discount: number;
  shipping: number;
  total: number;
  coupon?: string;
  paymentMethod: 'knet' | 'visa' | 'apple' | 'cod';
  paymentStatus: 'pending' | 'paid' | 'failed';
  status: 'placed' | 'paid' | 'preparing' | 'shipped' | 'delivered' | 'cancelled';
  loyaltyPointsEarned: number;
  loyaltyPointsUsed: number;
  createdAt: string;
  updatedAt: string;
}

export function getOrders(): Order[] { return readJSON<Order[]>('orders.json', []); }
export function saveOrders(orders: Order[]): void { writeJSON('orders.json', orders); }
export function getOrderById(id: string): Order | undefined { return getOrders().find(o => o.id === id); }
export function createOrder(order: Omit<Order, 'id' | 'createdAt' | 'updatedAt'>): Order {
  const orders = getOrders();
  const newOrder: Order = {
    ...order,
    id: 'FTP' + Math.random().toString(36).slice(2, 8).toUpperCase(),
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };
  orders.unshift(newOrder);
  saveOrders(orders);
  return newOrder;
}
export function updateOrderStatus(id: string, updates: Partial<Order>): Order | null {
  const orders = getOrders();
  const idx = orders.findIndex(o => o.id === id);
  if (idx === -1) return null;
  orders[idx] = { ...orders[idx], ...updates, updatedAt: new Date().toISOString() };
  saveOrders(orders);
  return orders[idx];
}

// ===== USERS / LOYALTY =====
export interface DBUser {
  id: string;
  name: string;
  email: string;
  password: string;
  phone: string;
  role: 'admin' | 'customer';
  loyaltyPoints: number;
  addresses: Address[];
  createdAt: string;
}
export interface Address {
  id: string;
  label: string;
  area: string;
  block: string;
  street: string;
  building: string;
  floor?: string;
  isDefault: boolean;
}
export function getUsers(): DBUser[] { return readJSON<DBUser[]>('users.json', [
  { id: '1', name: 'Admin User', email: 'admin@fasttimephone.kw', password: 'admin123', phone: '+96512345678', role: 'admin', loyaltyPoints: 0, addresses: [], createdAt: new Date().toISOString() },
]); }
export function saveUsers(users: DBUser[]): void { writeJSON('users.json', users); }
export function getUserByEmail(email: string): DBUser | undefined { return getUsers().find(u => u.email === email); }
export function getUserById(id: string): DBUser | undefined { return getUsers().find(u => u.id === id); }
export function addLoyaltyPoints(userId: string, points: number): void {
  const users = getUsers();
  const user = users.find(u => u.id === userId);
  if (user) { user.loyaltyPoints = (user.loyaltyPoints || 0) + points; saveUsers(users); }
}

// ===== REVIEWS =====
export interface Review {
  id: string;
  productId: string;
  userId: string;
  userName: string;
  rating: number;
  comment: string;
  status: 'pending' | 'approved' | 'rejected';
  createdAt: string;
}
export function getReviews(): Review[] { return readJSON<Review[]>('reviews.json', []); }
export function saveReviews(reviews: Review[]): void { writeJSON('reviews.json', reviews); }
export function getProductReviews(productId: string): Review[] { return getReviews().filter(r => r.productId === productId && r.status === 'approved'); }
export function createReview(review: Omit<Review, 'id' | 'createdAt'>): Review {
  const reviews = getReviews();
  const newReview: Review = { ...review, id: Date.now().toString(), createdAt: new Date().toISOString() };
  reviews.unshift(newReview);
  saveReviews(reviews);
  return newReview;
}

// ===== BANNERS =====
export interface Banner {
  id: string;
  title: string;
  titleAr: string;
  subtitle: string;
  subtitleAr: string;
  buttonText: string;
  buttonTextAr: string;
  buttonLink: string;
  image?: string;
  active: boolean;
  order: number;
}
export function getBanners(): Banner[] { return readJSON<Banner[]>('banners.json', [
  { id: '1', title: 'Next-Gen Mobile Tech', titleAr: 'تقنية الجيل القادم', subtitle: 'Premium devices delivered across Kuwait', subtitleAr: 'أجهزة متميزة تُوصّل عبر الكويت', buttonText: 'Shop Now', buttonTextAr: 'تسوق الآن', buttonLink: '/products', active: true, order: 1 },
]); }
export function saveBanners(banners: Banner[]): void { writeJSON('banners.json', banners); }

// ===== OFFERS =====
export interface Offer {
  id: string;
  type: 'percentage' | 'fixed' | 'bogo' | 'bundle';
  title: string;
  titleAr: string;
  minAmount?: number;
  discountValue: number;
  productIds?: string[];
  active: boolean;
  expiresAt?: string;
}
export function getOffers(): Offer[] { return readJSON<Offer[]>('offers.json', [
  { id: '1', type: 'percentage', title: 'First Purchase 10% Off', titleAr: 'خصم 10% للطلب الأول', discountValue: 10, active: true },
  { id: '2', type: 'fixed', title: 'Spend 50+ KWD, Save 5 KWD', titleAr: 'اشترِ بـ50+ د.ك وادخر 5', minAmount: 50, discountValue: 5, active: true },
]); }
export function saveOffers(offers: Offer[]): void { writeJSON('offers.json', offers); }

// ===== COUPONS =====
export interface Coupon {
  code: string;
  type: 'percentage' | 'fixed';
  value: number;
  minAmount?: number;
  maxUses?: number;
  usedCount: number;
  active: boolean;
  expiresAt?: string;
}
export function getCoupons(): Coupon[] { return readJSON<Coupon[]>('coupons.json', [
  { code: 'SAVE10', type: 'percentage', value: 10, usedCount: 0, active: true },
  { code: 'WELCOME20', type: 'percentage', value: 20, usedCount: 0, active: true },
  { code: 'FTP5KWD', type: 'fixed', value: 5, minAmount: 30, usedCount: 0, active: true },
]); }
export function saveCoupons(coupons: Coupon[]): void { writeJSON('coupons.json', coupons); }
export function validateCoupon(code: string, amount: number): { valid: boolean; coupon?: Coupon; message: string } {
  const coupons = getCoupons();
  const coupon = coupons.find(c => c.code === code.toUpperCase() && c.active);
  if (!coupon) return { valid: false, message: 'Invalid coupon code' };
  if (coupon.expiresAt && new Date(coupon.expiresAt) < new Date()) return { valid: false, message: 'Coupon expired' };
  if (coupon.minAmount && amount < coupon.minAmount) return { valid: false, message: `Minimum order: ${coupon.minAmount} KWD` };
  if (coupon.maxUses && coupon.usedCount >= coupon.maxUses) return { valid: false, message: 'Coupon limit reached' };
  return { valid: true, coupon, message: 'Coupon applied!' };
}

// ===== ANALYTICS =====
export interface AnalyticsDay {
  date: string;
  revenue: number;
  orders: number;
  newUsers: number;
}
export function getAnalytics(): AnalyticsDay[] {
  // Generate last 30 days of mock data
  const days: AnalyticsDay[] = [];
  for (let i = 29; i >= 0; i--) {
    const d = new Date();
    d.setDate(d.getDate() - i);
    days.push({
      date: d.toISOString().split('T')[0],
      revenue: Math.floor(Math.random() * 1500 + 400),
      orders: Math.floor(Math.random() * 20 + 5),
      newUsers: Math.floor(Math.random() * 10 + 1),
    });
  }
  return days;
}
