import ClubVenue from '../models/ClubVenue.js';
import { checkAccess } from '../utils/userUtils.js';
import HttpError from '../exceptions/HttpError.js';

const clean = (value) => String(value || '').trim();
const cleanNullable = (value) => clean(value) || null;

class ClubVenueService {
  async list(userToken, clubId) {
    await checkAccess(userToken, clubId);
    return ClubVenue.findAll({
      where: { clubId },
      order: [['sortOrder', 'ASC'], ['name', 'ASC'], ['id', 'ASC']],
    });
  }

  async create(userToken, clubId, payload = {}) {
    await checkAccess(userToken, clubId);
    const name = clean(payload.name);
    if (!name) throw new HttpError('Name ist erforderlich', 400);
    const maxSortOrder = await ClubVenue.max('sortOrder', { where: { clubId } }) || 0;
    return ClubVenue.create({
      clubId,
      name,
      address: cleanNullable(payload.address),
      zip: cleanNullable(payload.zip),
      city: cleanNullable(payload.city),
      sortOrder: Number.isFinite(Number(payload.sortOrder)) ? Number(payload.sortOrder) : maxSortOrder + 1,
    });
  }

  async update(userToken, clubId, venueId, payload = {}) {
    await checkAccess(userToken, clubId);
    const venue = await ClubVenue.findOne({ where: { id: venueId, clubId } });
    if (!venue) throw new HttpError('Spiellokal nicht gefunden', 404);
    const updates = {};
    if (payload.name !== undefined) {
      const name = clean(payload.name);
      if (!name) throw new HttpError('Name ist erforderlich', 400);
      updates.name = name;
    }
    if (payload.address !== undefined) updates.address = cleanNullable(payload.address);
    if (payload.zip !== undefined) updates.zip = cleanNullable(payload.zip);
    if (payload.city !== undefined) updates.city = cleanNullable(payload.city);
    if (payload.sortOrder !== undefined && Number.isFinite(Number(payload.sortOrder))) updates.sortOrder = Number(payload.sortOrder);
    return venue.update(updates);
  }

  async delete(userToken, clubId, venueId) {
    await checkAccess(userToken, clubId);
    const venue = await ClubVenue.findOne({ where: { id: venueId, clubId } });
    if (!venue) throw new HttpError('Spiellokal nicht gefunden', 404);
    await venue.destroy();
    return { success: true };
  }
}

export default new ClubVenueService();
