ALTER TABLE role_permissions RENAME TO role_permissions_legacy;
CREATE TABLE role_permissions (
  role TEXT NOT NULL CHECK(role IN ('admin','responsable','benevole','lecture')),
  module TEXT NOT NULL CHECK(module IN ('dashboard','animals','medical','care','directory','agenda','statistics','administrative','grants')),
  can_view INTEGER NOT NULL DEFAULT 0 CHECK(can_view IN (0,1)),
  can_edit INTEGER NOT NULL DEFAULT 0 CHECK(can_edit IN (0,1)),
  updated_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
  updated_at TEXT NOT NULL DEFAULT(datetime('now')),
  PRIMARY KEY(role,module)
);
INSERT INTO role_permissions SELECT * FROM role_permissions_legacy;
DROP TABLE role_permissions_legacy;
INSERT INTO role_permissions(role,module,can_view,can_edit) VALUES
('admin','agenda',1,1),('responsable','agenda',1,1),('benevole','agenda',1,1),('lecture','agenda',1,0);

CREATE TABLE agenda_items (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  item_type TEXT NOT NULL CHECK(item_type IN ('appointment','veterinary','transport','pre_adoption','task','other')),
  title TEXT NOT NULL,
  description TEXT,
  starts_at TEXT NOT NULL,
  ends_at TEXT,
  all_day INTEGER NOT NULL DEFAULT 0 CHECK(all_day IN (0,1)),
  location TEXT,
  status TEXT NOT NULL DEFAULT 'planned' CHECK(status IN ('planned','completed','cancelled')),
  priority TEXT NOT NULL DEFAULT 'normal' CHECK(priority IN ('low','normal','high','urgent')),
  assigned_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
  animal_id INTEGER REFERENCES animals(id) ON DELETE SET NULL,
  contact_id INTEGER REFERENCES directory_contacts(id) ON DELETE SET NULL,
  reminder_minutes INTEGER CHECK(reminder_minutes IS NULL OR reminder_minutes >= 0),
  repeat_rule TEXT NOT NULL DEFAULT 'none' CHECK(repeat_rule IN ('none','daily','weekly','monthly')),
  repeat_until TEXT,
  completed_at TEXT,
  completed_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
  created_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
  created_at TEXT NOT NULL DEFAULT(datetime('now')),
  updated_at TEXT NOT NULL DEFAULT(datetime('now'))
);
CREATE INDEX idx_agenda_starts ON agenda_items(starts_at,status);
CREATE INDEX idx_agenda_assignee ON agenda_items(assigned_user_id,status,starts_at);
CREATE INDEX idx_agenda_animal ON agenda_items(animal_id,starts_at);
